架构与系统设计 / 系统课时
为订单模型加入领域行为
为订单模型加入领域行为
确定订单聚合边界后,还需要把业务规则真正放进模型。如果应用 Service 可以任意调用 Setter 修改状态、金额和明细,聚合边界仍然只是结构上的分组。本节把“添加明细”和“支付订单”封装成领域行为,让对象自己阻止非法状态变化。
学习目标
- 把订单状态变化和金额维护封装为聚合行为
- 避免应用 Service 直接修改订单内部字段
- 使用可运行示例验证领域行为能够保护业务不变量
从数据对象转向行为对象
贫血模型常把 Order 写成只有字段和 Getter/Setter 的数据结构,再让 Service 完成所有判断。例如 Service 先检查订单状态,再修改明细集合,最后重新计算总金额。规则分散后,其他调用方只要漏掉其中一步,就可能制造非法订单。
领域模型更合适的接口应表达业务意图,例如 addItem、pay,而不是 setStatus、setTotalAmount。聚合根收到命令后,在内部检查当前状态、修改明细并维护派生数据,调用方无法绕开这些规则。
在聚合根中封装规则
下面用一个可直接运行的 Java 示例实现订单聚合。为了聚焦领域行为,示例使用内存对象,不包含仓储和数据库代码。
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class OrderDomainDemo {
enum OrderStatus {
PENDING, PAID
}
static final class OrderLine {
private final String productId;
private final int quantity;
private final BigDecimal unitPrice;
OrderLine(String productId, int quantity, BigDecimal unitPrice) {
if (quantity <= 0) {
throw new IllegalArgumentException("quantity must be positive");
}
if (unitPrice.signum() < 0) {
throw new IllegalArgumentException("unitPrice cannot be negative");
}
this.productId = productId;
this.quantity = quantity;
this.unitPrice = unitPrice;
}
BigDecimal subtotal() {
return unitPrice.multiply(BigDecimal.valueOf(quantity));
}
String productId() {
return productId;
}
}
static final class Order {
private final String id;
private final List<OrderLine> lines = new ArrayList<>();
private OrderStatus status = OrderStatus.PENDING;
private BigDecimal totalAmount = BigDecimal.ZERO;
Order(String id) {
this.id = id;
}
void addItem(String productId, int quantity, BigDecimal unitPrice) {
ensureEditable();
lines.add(new OrderLine(productId, quantity, unitPrice));
// 金额由聚合内部根据明细重新计算,调用方不能单独覆盖它。
recalculateTotal();
}
void pay() {
if (status != OrderStatus.PENDING) {
throw new IllegalStateException("order is not pending");
}
if (lines.isEmpty()) {
throw new IllegalStateException("empty order cannot be paid");
}
status = OrderStatus.PAID;
}
private void ensureEditable() {
if (status != OrderStatus.PENDING) {
throw new IllegalStateException("paid order cannot be changed");
}
}
private void recalculateTotal() {
totalAmount = lines.stream()
.map(OrderLine::subtotal)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
BigDecimal totalAmount() {
return totalAmount;
}
OrderStatus status() {
return status;
}
List<OrderLine> lines() {
return Collections.unmodifiableList(lines);
}
}
public static void main(String[] args) {
Order order = new Order("ORDER-1001");
order.addItem("P-100", 2, new BigDecimal("39.90"));
order.addItem("P-200", 1, new BigDecimal("20.00"));
System.out.println("total=" + order.totalAmount());
order.pay();
System.out.println("status=" + order.status());
try {
order.addItem("P-300", 1, new BigDecimal("10.00"));
} catch (IllegalStateException e) {
System.out.println("rejected=" + e.getMessage());
}
}
}预期输出
total=99.80
status=PAID
rejected=paid order cannot be changed示例中的关键点不是把校验代码搬进实体,而是让所有可能破坏订单不变量的入口都受聚合控制。totalAmount 没有公开 Setter,明细列表也通过只读视图暴露,因此外部代码无法直接插入一条明细而跳过金额重算。
让 Service 只负责协调
应用 Service 仍然有价值,但它的职责应是加载聚合、调用领域行为并保存结果,而不是重新实现订单规则。典型流程是先通过仓储取得订单,然后调用 order.addItem(...) 或 order.pay(),最后提交聚合。
这样做可以把“订单为什么允许修改”保留在 Order 内。无论行为由 HTTP 接口、消息消费者还是批处理任务触发,只要最终调用同一个领域方法,就会经过相同规则。
设计行为时关注不变量
判断一条规则是否应进入聚合,可以问两个问题:如果绕过这条规则,对象是否立即进入非法状态;执行这个行为时,是否需要同时修改聚合内部多个数据。如果答案是肯定的,规则通常应该由聚合根保护。
例如“已支付订单不能再改明细”属于订单自身的不变量,应放在 Order;而“支付成功后给用户增加积分”涉及另一个聚合,通常不应让 Order 直接修改用户积分。订单可以完成自己的状态变化,再由应用协调或领域事件触发后续处理。
领域行为的最终目标不是让实体拥有更多方法,而是让非法状态难以被构造。外部代码只表达“想做什么”,聚合负责判断“现在能不能做”以及“做完后哪些内部数据必须一起改变”,订单模型才真正承担起业务规则的职责。