← 中文资源

简体中文版本

聚合根

聚合根是必须一起保持一致的对象簇的唯一入口,定义了原子变更的边界以及并发冲突的检测单位。

阅读英文原文

概念概述

聚合根(Aggregate Root)指的是:聚合根是必须一起保持一致的对象簇的唯一入口,定义了原子变更的边界以及并发冲突的检测单位。

从更严格的定义看,An aggregate root is an entity that guards a consistency boundary, owning other objects and exposing them only through itself so that all invariants inside the boundary are enforced in one transaction. 该概念在工程实践中的价值,在于它能帮助团队用统一的语言描述一个具体的质量属性或设计约束,从而在评审与协作中减少歧义。

为什么需要它

It is used in domain-driven designs to decide what can change atomically and how concurrency conflicts are detected. 它与 Repository Pattern、Unit of Work、Publish-Subscribe Messaging 等概念经常一起出现,用于解决相近的工程问题。理解它的适用场景,有助于在多种备选方案之间做出有依据的取舍,而不是凭直觉选择技术方案。

常见误解

  • every entity in a model is an aggregate root
  • an aggregate must include everything related to it

需要避免的反模式

  • referencing another aggregate by object instead of by identity
  • making an aggregate of aggregate so large it locks the whole graph

实践要点

  1. The root is the only object outside code may hold a reference to, and other aggregates are referenced by identifier so that each boundary remains independently consistent.
  2. A well-sized aggregate loads and commits in one transaction, which keeps invariants enforceable without long-lived locks across many rows.
  3. Oversized aggregates cause contention and force large loads, so the boundary should be the smallest set of objects that must be consistent at one instant.

参考来源

https://martinfowler.com/bliki/DDD_Aggregate.html