4.5实体与值对象

分类: DDD领域驱动设计实战

实体与值对象

实体和值对象是领域模型的基本构建块。理解它们的区别和设计原则是 DDD 设计的基础。本节将学习如何设计实体和值对象。

本节将学习:实体设计、值对象设计、领域事件,以及领域模型实现。

实体设计

实体特点

实体特点:

  • 有唯一标识(ID)
  • 可变性
  • 生命周期管理

实体示例

public class User { private Long id; // 唯一标识 private String username; private String email; private UserProfile profile; // 值对象 // 实体方法 public void updateProfile(UserProfile profile) { this.profile = profile; } }

值对象设计

值对象特点

值对象特点:

  • 无唯一标识
  • 不可变性
  • 值相等性

值对象示例

public class Money { private final BigDecimal amount; private final String currency; public Money(BigDecimal amount, String currency) { this.amount = amount; this.currency = currency; } public Money add(Money other) { if (!this.currency.equals(other.currency)) { throw new IllegalArgumentException("Currency mismatch"); } return new Money(this.amount.add(other.amount), this.currency); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Money money = (Money) o; return Objects.equals(amount, money.amount) && Objects.equals(currency, money.currency); } }

领域事件

领域事件定义

领域事件 是领域模型中发生的重要事件。

领域事件示例

public class OrderCreatedEvent { private final Long orderId; private final Long userId; private final BigDecimal totalAmount; private final LocalDateTime occurredOn; public OrderCreatedEvent(Long orderId, Long userId, BigDecimal totalAmount) { this.orderId = orderId; this.userId = userId; this.totalAmount = totalAmount; this.occurredOn = LocalDateTime.now(); } }

官方资源

本节小结

在本节中,我们学习了:

第一个是实体设计。 实体有唯一标识,可变。

第二个是值对象设计。 值对象无标识,不可变。

第三个是领域事件。 领域事件表示领域中的重要事件。

这就是实体与值对象设计。理解它们的区别,是设计领域模型的基础。

在下一节,我们将学习如何实现 Repository 模式。