知识卡片
简单创建可以直接用构造器
对象没有需要隐藏的多态实现,调用方关心具体类、掌握全部属性,且构造过程简单时,公开构造器更直接。它仍须一次完成初始化并满足不变量;不要在构造器里层层创建其他类或装配复杂聚合。原书讨论 Java 集合构造器只是当时库设计的权衡例子,不等于所有集合都应直接构造。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 原书第06章|Factories · 查看原书依据
The trade-offs favor a bare, public constructor in the following circumstances. The class is the type. It is not part of any interesting hierarchy, and it isn't used polymorphically by implementing an interface.
参考来源
- 位置:《Domain-Driven Design: Tackling Complexity in the Heart of Software》第45章《原书第06章|Factories》(源文件:_epub-src/0321125215_ch06lev1sec2.html;小节 When a Constructor Is All You Need)
- 结论依据:原文列出公开构造器适用条件,并要求其保持原子、不变量有效、实现简单;随后用 Java 集合说明抽象与具体选择的权衡。
- 原始内容:The trade-offs favor a bare, public constructor in the following circumstances. The class is the type. It is not part of any interesting hierarchy, and it isn't used polymorphically by implementing an interface. ... A public constructor must follow the same rules as a FACTORY : It must be an atomic operation that satisfies all invariants of the created object.