良好的类建模意味着类映射到真实的域概念,每个类有一个明确的责任,通过诚实的is-a/has-a关系相互关联,并在边界处依赖于抽象。没有公式,但有一个可重复的过程。
实用过程
text
1. Find the NOUNS → candidate classes (Order, Customer, Payment)
2. Find the VERBS → candidate behaviors/methods (place, refund, ship)
3. Assign each behavior to the class that OWNS the data it needs (high cohesion)
4. Choose relationships: IS-A (rare, must pass LSP) vs HAS-A (default)
5. Depend on interfaces at boundaries (DIP); inject volatile dependencies
6. Keep invariants inside the object (encapsulation); prefer immutability for values
行为遵循数据
java
{ List<Item> items; }
{ {...} }
{
List<Item> items;
Money {
items.stream().map(Item::price).reduce(Money.ZERO, Money::plus);
}
}
