架构与系统设计 / 系统课时

先建立订单领域模型

先建立订单领域模型

重构订单模块时,第一步不是创建更多 Service,而是让订单自己维护价格与状态规则。一个可用的订单聚合应保证任何调用者都不能随意写状态,也不能绕过金额计算;应用层只负责加载聚合、调用行为并保存结果。

学习目标

  • 以订单为聚合根组织订单项、金额和状态
  • 把价格计算与状态迁移规则封装为领域行为
  • 理解为什么应用层应调用行为而不是直接修改字段

从聚合不变量开始设计

订单模型最重要的不是字段齐全,而是明确哪些条件在任何时刻都必须成立。例如:空订单不能提交;只有已提交订单才能支付;订单总价必须由订单项计算,而不是由外部调用者随意传入一个总金额。

这些规则都依赖订单自身状态,因此适合放进 Order 聚合。聚合根对外暴露 addItem、submit、markPaid 等行为,而不提供任意设置 status 或 totalAmount 的入口。

订单聚合边界与规则归属图

用代码把规则放回订单

下面的示例可以直接编译运行。Order 只允许通过行为改变状态,总价始终从订单项计算,因此调用者无法制造“状态合法但金额错误”的订单。

java
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class OrderDomainDemo {
    enum OrderStatus { DRAFT, SUBMITTED, PAID }

    record OrderLine(String productId, int quantity, BigDecimal unitPrice) {
        OrderLine {
            if (quantity <= 0) {
                throw new IllegalArgumentException("quantity must be positive");
            }
            if (unitPrice.signum() < 0) {
                throw new IllegalArgumentException("unitPrice cannot be negative");
            }
        }

        BigDecimal subtotal() {
            return unitPrice.multiply(BigDecimal.valueOf(quantity));
        }
    }

    static class Order {
        private final long id;
        private final List<OrderLine> lines = new ArrayList<>();
        private OrderStatus status = OrderStatus.DRAFT;

        Order(long id) {
            this.id = id;
        }

        void addItem(String productId, int quantity, BigDecimal unitPrice) {
            ensureStatus(OrderStatus.DRAFT);
            lines.add(new OrderLine(productId, quantity, unitPrice));
        }

        BigDecimal totalAmount() {
            return lines.stream()
                    .map(OrderLine::subtotal)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
        }

        void submit() {
            ensureStatus(OrderStatus.DRAFT);
            if (lines.isEmpty()) {
                throw new IllegalStateException("empty order cannot be submitted");
            }
            status = OrderStatus.SUBMITTED;
        }

        void markPaid() {
            ensureStatus(OrderStatus.SUBMITTED);
            status = OrderStatus.PAID;
        }

        OrderStatus status() {
            return status;
        }

        private void ensureStatus(OrderStatus expected) {
            if (status != expected) {
                throw new IllegalStateException(
                        "expected " + expected + " but was " + status);
            }
        }
    }

    public static void main(String[] args) {
        Order order = new Order(1001L);
        order.addItem("P-01", 2, new BigDecimal("19.90"));
        order.addItem("P-02", 1, new BigDecimal("8.50"));

        System.out.println("total=" + order.totalAmount());
        order.submit();
        order.markPaid();
        System.out.println("status=" + order.status());
    }
}

预期输出

text
total=48.30
status=PAID

这里的关键不是把原 Service 方法搬进 Order,而是让对象拥有保持自身正确性的能力。外部代码只能请求“提交订单”或“标记已支付”,不能执行 order.status = ... 之类的直接赋值。

让应用层只做用例编排

重构后,支付用例的典型顺序是:通过仓储加载订单,读取应支付金额,调用支付网关,支付成功后调用 order.markPaid(),最后保存订单。应用层知道流程顺序,但不知道“什么状态允许支付”的判断细节。

仓储也应以聚合为单位工作。应用层面对的是 OrderRepository 这类抽象,基础设施层再决定使用 JPA、MyBatis 或其他持久化方式。这样数据库表结构不会反过来决定领域对象必须暴露哪些可写字段。

检查模型是否真的完成了迁移

一个订单领域模型至少应满足三个检查点:状态字段不能被外部任意改写;金额由订单项等领域数据推导;非法状态迁移在聚合内部被拒绝。满足这些条件后,应用层才能逐步瘦身为清晰的用例编排,而不是继续承载订单规则。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

先建立订单领域模型

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通