上一篇文章讲了repository的实现。结合前面的文章基本把ddd战术篇中的登场人物都介绍了一遍。依次是如下几个角色。
首先是位于domain层的domain objects
- aggregate
- entity
- value object
- domain service
- repository
- specification
- factory
另外有还有两种service。application service, infrastructure service.
当我们分析业务,实际建模时,最重要的当然是aggregate, entity与value object。
我们会将业务逻辑尽量写进entity与value object。
而aggregate还有确保数据完整性的责任。entity,value object也最终隶属于某个aggregate。(value object如果不需要永久化的话,那它可以独立于aggregate)
因此aggregate的设计是十分重要的,这篇文章就来谈谈aggregate的设计策略。
尽量设计小aggregate?
什么是小aggregate?
那我们先看看什么是大的吧~
如果所示,root entity直接引用了很多的entity。
我们用例子来说明一下。假设我们对处理一个教室物品管理的问题。教室里有椅子,桌子和黑板这些物品,为了解释数据完整性的问题,假设一个教室里不能有超过50样物品。另一个需求是假设这些物品需要维护,要记录各个物品是在何时维护的。
大概是这么一个关系
比较直观的方案当然是把教室当作一个aggregate,里边有它的物品。
首先是教室类,他是一个entity
public class Classroom {
private ClassroomId classroomId;
private String classRoomNo; // eg: 402
private List<Item> items;
public Item add(Item item) throws ItemLimitExceededException {
if(items.size() == 50) {
throw new ItemLimitExceededException();
}