我找不到任何清楚的示例,说明如何使用JavaScript/TypeScript正确封装聚合根(DDD)的内部状态来实现它。下面我就如何实现它提出一个建议。也许有人对如何改进这个解决方案有自己的想法:
import cloneDeep from 'clone-deep';
import { deepFreeze } from '../utils'; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
export class AggregateRoot<TEntityProps> {
// TODO EntityId
protected readonly props: TEntityProps
constructor(props: TEntityProps) {
/** Encapsulate aggregate's state from the outside world */
this.props = cloneDeep<TEntityProps>(props)
}
/** Extract the state from an aggregate.
*
* Aggregate becomes unchangeable (read-only) after calling the flush method.
* */
public flush(): TEntityProps {
return deepFreeze(this.props)
}
}
// Usage
export class User extends AggregateRoot<UserProps> {
constructor(props: UserProps) {
super(props)
// props validation here
}
get firstName() {
return this.props.firstName
}
get lastName() {
return this.props.lastName
}
get updatedAt() {
return this.props.updatedAt
}
}发布于 2022-02-08 19:18:59
另一个变体是重写此方法:
public flush(): TEntityProps {
return deepFreeze(this.props)
}使用
public snapshot(): TEntityProps {
return cloneDeep(this.props)
}但我们需要知道,在这种情况下,我们增加了两次内存消耗。因此,我认为,它很可能适合于小型聚集体。
https://stackoverflow.com/questions/71039672
复制相似问题