知识卡片
不可变使值对象安全共享
两个实体可以共享同一个值对象实例,前提是该值对象不可变;修改时应以新值整体替换。否则两个人共享 Name 后,给一人改名会意外改变另一人的名字。把可变值对象作为参数或返回值传出,也可能让外部修改破坏拥有者的不变量;可选择不可变对象或传副本。这里的不可变是保护共享语义的设计约束,具体语言能否直接声明还需靠实现纪律。参见[[值对象按描述而非身份理解]]。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 原书第05章|Is "Address" a V ALUE O BJECT ? Who's Asking? · 查看原书依据
To protect against this, in order for an object to be shared safely, it must be immutable: it cannot be changed except by full replacement.
参考来源
- 位置:《Domain-Driven Design: Tackling Complexity in the Heart of Software》第38章《原书第05章|Is "Address" a V ALUE O BJECT ? Who's Asking?》(源文件:_epub-src/0321125215_ch05lev1sec3_split_001.html)
- 结论依据:原文以两个人共享 Name 后的改名串扰说明共享须不可变,也指出跨对象传参或返回可变值会破坏持有者约束,副本是另一种规避方式。
- 原始内容:To protect against this, in order for an object to be shared safely, it must be immutable : it cannot be changed except by full replacement. ... This problem is avoided either by making the passed object immutable, or by passing a copy.