← 返回首页 📚 实战课程
📑 本篇章节导航 (共5章,点击直达)
一、理论篇:DDD核心概念(30%)二、实战篇:OTA定价系统DDD重构(40%)三、面试模拟篇(20%)四、练习篇(10%)DDD落地关键原则

P4-05 DDD架构实践

适用对象:5年经验Java开发者,目标薪资18-22K
课时:约3.5小时 | 理论30% + 实战40% + 面试20% + 练习10%

一、理论篇:DDD核心概念(30%)

1.1 为什么需要DDD

传统MVC架构的问题:

DDD的核心思想:让代码结构反映业务结构,用业务语言来写代码。

1.2 DDD核心概念

限界上下文(Bounded Context)

一个大的业务域被划分为多个限界上下文,每个上下文有自己的模型、语言和边界。


┌─────────────────────────────────────────────────────┐
│                    OTA订票系统                         │
├──────────────┬──────────────┬────────────────────────┤
│  订单上下文    │  定价上下文    │  库存上下文             │
│  OrderContext │ PricingCtx   │  InventoryContext      │
│              │              │                        │
│ - 创建订单    │ - 计算价格    │ - 查询余票              │
│ - 取消订单    │ - 折扣策略    │ - 锁定座位              │
│ - 支付订单    │ - 会员价格    │ - 释放座位              │
│              │              │                        │
│ Order(聚合根) │ PricePlan    │ Seat(聚合根)            │
└──────────────┴──────────────┴────────────────────────┘

聚合根(Aggregate Root)

聚合是一组相关对象的集合,聚合根是聚合的入口。

规则:


// Order是聚合根,OrderItem是聚合内的实体
// 外部不能直接操作OrderItem,必须通过Order
Aggregate: Order(聚合根)
  ├── OrderItem(实体)
  ├── OrderItem(实体)
  └── Address(值对象)

领域事件(Domain Event)

领域中发生的、有业务意义的事件,用于解耦聚合间通信。


// 订单创建事件
public class OrderCreatedEvent extends DomainEvent {
    private String orderNo;
    private Long userId;
    private BigDecimal amount;
}

// 订单创建后 → 发送事件 → 库存上下文监听并锁定座位

仓储模式(Repository)

聚合根的持久化抽象,隔离领域模型与数据访问技术。


// 领域层只依赖接口
public interface OrderRepository {
    Order findById(OrderId id);
    void save(Order order);
    void remove(Order order);
}

1.3 DDD分层架构


┌──────────────────────────────────────────┐
│  Interface(接口层)                       │
│  Controller / DTO /Assembler             │
├──────────────────────────────────────────┤
│  Application(应用层)                     │
│  ApplicationService / Command / Query    │
│  编排领域对象,不包含业务逻辑               │
├──────────────────────────────────────────┤
│  Domain(领域层)★ 核心                    │
│  AggregateRoot / Entity / ValueObject    │
│  DomainService / DomainEvent            │
│  Repository(接口)                         │
├──────────────────────────────────────────┤
│  Infrastructure(基础设施层)              │
│  RepositoryImpl / MQ / Cache / Config   │
└──────────────────────────────────────────┘

依赖方向:Interface → Application → Domain ← Infrastructure
                  │           │              ↑
                  └───────────┴──────────────┘
         Infrastructure实现Domain层定义的接口(依赖倒置)

1.4 CQRS模式

命令与查询职责分离(Command Query Responsibility Segregation):


         ┌──────────┐
用户 ──→ │  Command  │ ──→ 写模型(主库)──→ 领域事件 ──→ 读模型(ES/Redis)
         │  (写操作)  │
         └──────────┘

用户 ──→ │  Query    │ ──→ 读模型(从库/缓存)──→ 返回DTO
         │  (读操作)  │
         └──────────┘

二、实战篇:OTA定价系统DDD重构(40%)

2.1 包结构


com.example.ota.pricing
├── interface/                     # 接口层
│   ├── controller/
│   │   └── PricingController.java
│   ├── dto/
│   │   ├── PriceQueryRequest.java
│   │   └── PriceQueryResponse.java
│   └── assembler/
│       └── PriceAssembler.java    # DTO ↔ 领域对象转换
├── application/                   # 应用层
│   ├── service/
│   │   └── PricingApplicationService.java
│   ├── command/
│   │   └── CalculatePriceCommand.java
│   └── query/
│       └── PriceQueryService.java
├── domain/                        # 领域层(核心)
│   ├── model/
│   │   ├── aggregate/
│   │   │   └── PricePlan.java     # 聚合根
│   │   ├── entity/
│   │   │   ├── PriceTier.java     # 价格档位(实体)
│   │   │   └── DiscountRule.java  # 折扣规则(实体)
│   │   └── valueobject/
│   │       ├── Money.java         # 金额值对象
│   │       ├── PriceType.java     # 价格类型枚举
│   │       └── DateRange.java     # 日期范围值对象
│   ├── service/
│   │   └── PricingDomainService.java
│   ├── event/
│   │   ├── PriceCalculatedEvent.java
│   │   └── PriceChangedEvent.java
│   └── repository/
│       └── PricePlanRepository.java  # 仓储接口
└── infrastructure/                # 基础设施层
    ├── repository/
    │   └── PricePlanRepositoryImpl.java
    ├── persistence/
    │   ├── mapper/
    │   │   └── PricePlanMapper.java
    │   └── po/
    │       └── PricePlanPO.java
    ├── mq/
    │   └── DomainEventPublisher.java
    └── config/
        └── PricingConfig.java

2.2 值对象


/**
 * 金额值对象 - 不可变
 * 值对象的特点:无唯一标识、不可变、通过属性判断相等
 */
public class Money {
    private final BigDecimal amount;
    private final String currency;

    public Money(BigDecimal amount, String currency) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("金额不能为负数");
        }
        this.amount = amount.setScale(2, RoundingMode.HALF_UP);
        this.currency = currency;
    }

    public static Money of(BigDecimal amount) {
        return new Money(amount, "CNY");
    }

    public static Money zero() {
        return new Money(BigDecimal.ZERO, "CNY");
    }

    public Money add(Money other) {
        return new Money(this.amount.add(other.amount), this.currency);
    }

    public Money subtract(Money other) {
        return new Money(this.amount.subtract(other.amount), this.currency);
    }

    public Money multiply(int quantity) {
        return new Money(
            this.amount.multiply(BigDecimal.valueOf(quantity)), this.currency);
    }

    public Money multiply(BigDecimal factor) {
        return new Money(
            this.amount.multiply(factor).setScale(2, RoundingMode.HALF_UP), 
            this.currency);
    }

    public boolean isGreaterThan(Money other) {
        return this.amount.compareTo(other.amount) > 0;
    }

    // 只提供getter,不提供setter(不可变)
    public BigDecimal getAmount() { return amount; }
    public String getCurrency() { return currency; }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Money)) return false;
        Money money = (Money) o;
        return amount.equals(money.amount) && currency.equals(money.currency);
    }
}

2.3 聚合根


/**
 * 定价方案 - 聚合根
 * 所有对价格档位和折扣规则的访问和修改都通过这个类
 */
public class PricePlan {
    // 聚合根唯一标识
    private PricePlanId id;
    private String planName;
    private String routeId;          // 航线ID
    private PriceType priceType;     // 经济舱/商务舱/头等舱
    private DateRange effectiveDate; // 有效期(值对象)
    private List<PriceTier> priceTiers; // 价格档位(实体列表)
    private List<DiscountRule> discountRules; // 折扣规则
    private boolean active;
    private List<DomainEvent> domainEvents; // 领域事件

    // ====== 工厂方法 ======
    public static PricePlan create(String planName, String routeId,
            PriceType priceType, DateRange effectiveDate) {
        PricePlan plan = new PricePlan();
        plan.id = new PricePlanId(IdWorker.getIdStr());
        plan.planName = planName;
        plan.routeId = routeId;
        plan.priceType = priceType;
        plan.effectiveDate = effectiveDate;
        plan.priceTiers = new ArrayList<>();
        plan.discountRules = new ArrayList<>();
        plan.domainEvents = new ArrayList<>();
        plan.active = true;
        return plan;
    }

    // ====== 业务方法(聚合根保护内部一致性)======

    /**
     * 添加价格档位
     * 业务规则:同一日期范围不能有重叠的档位
     */
    public void addPriceTier(PriceTier tier) {
        // 验证档位日期不重叠
        for (PriceTier existing : priceTiers) {
            if (existing.getDateRange().overlaps(tier.getDateRange())) {
                throw new DomainException(
                    "价格档位日期范围冲突: " + tier.getDateRange());
            }
        }
        priceTiers.add(tier);
    }

    /**
     * 添加折扣规则
     */
    public void addDiscountRule(DiscountRule rule) {
        discountRules.add(rule);
    }

    /**
     * 计算价格(核心领域逻辑)
     * 根据日期查找匹配的档位 → 应用折扣规则 → 返回最终价格
     */
    public Money calculatePrice(LocalDateTime travelDate, 
            Integer quantity, MemberLevel memberLevel) {
        // 1. 校验有效期
        if (!effectiveDate.contains(travelDate)) {
            throw new DomainException("不在定价方案有效期内");
        }
        if (!active) {
            throw new DomainException("定价方案未启用");
        }

        // 2. 查找匹配的价格档位
        PriceTier matchedTier = priceTiers.stream()
            .filter(t -> t.matches(travelDate))
            .findFirst()
            .orElseThrow(() -> new DomainException(
                "未找到匹配的价格档位"));

        // 3. 计算基础价格 = 单价 x 数量
        Money basePrice = matchedTier.getUnitPrice().multiply(quantity);

        // 4. 应用折扣规则
        Money discount = Money.zero();
        for (DiscountRule rule : discountRules) {
            if (rule.isApplicable(memberLevel, quantity)) {
                discount = discount.add(rule.calculateDiscount(basePrice));
            }
        }

        Money finalPrice = basePrice.subtract(discount);

        // 5. 发布领域事件
        registerEvent(new PriceCalculatedEvent(
            this.id, travelDate, quantity, basePrice, finalPrice
        ));

        return finalPrice;
    }

    /**
     * 停用定价方案
     */
    public void deactivate(String reason) {
        this.active = false;
        registerEvent(new PriceChangedEvent(this.id, "DEACTIVATED", reason));
    }

    // ====== 领域事件管理 ======
    private void registerEvent(DomainEvent event) {
        this.domainEvents.add(event);
    }

    public List<DomainEvent> getDomainEvents() {
        return Collections.unmodifiableList(domainEvents);
    }

    public void clearDomainEvents() {
        domainEvents.clear();
    }

    // getter方法(省略部分)
    public PricePlanId getId() { return id; }
    public String getRouteId() { return routeId; }
    public PriceType getPriceType() { return priceType; }
}

2.4 领域服务


/**
 * 定价领域服务
 * 处理跨聚合根的逻辑,或不太适合放在单一聚合根中的逻辑
 */
@Service
public class PricingDomainService {

    private final PricePlanRepository pricePlanRepository;

    public PricingDomainService(PricePlanRepository pricePlanRepository) {
        this.pricePlanRepository = pricePlanRepository;
    }

    /**
     * 获取最优价格(跨多个定价方案比较)
     */
    public Money getBestPrice(String routeId, PriceType priceType,
            LocalDateTime travelDate, Integer quantity, 
            MemberLevel memberLevel) {

        // 查找该航线、该舱位的所有有效定价方案
        List<PricePlan> plans = pricePlanRepository
            .findActiveByRouteAndType(routeId, priceType);

        if (plans.isEmpty()) {
            throw new DomainException("未找到有效的定价方案");
        }

        // 比较所有方案,取最低价
        Money bestPrice = null;
        for (PricePlan plan : plans) {
            try {
                Money price = plan.calculatePrice(
                    travelDate, quantity, memberLevel);
                if (bestPrice == null || price.isGreaterThan(bestPrice)) {
                    bestPrice = price;
                }
            } catch (DomainException e) {
                // 该方案不匹配,跳过
            }
        }

        if (bestPrice == null) {
            throw new DomainException("没有匹配的价格方案");
        }
        return bestPrice;
    }
}

2.5 仓储实现


// =================== 领域层:仓储接口 ===================
public interface PricePlanRepository {
    PricePlan findById(PricePlanId id);
    List<PricePlan> findActiveByRouteAndType(String routeId, 
        PriceType priceType);
    void save(PricePlan pricePlan);
    void remove(PricePlanId id);
}

// =================== 基础设施层:仓储实现 ===================
@Repository
public class PricePlanRepositoryImpl implements PricePlanRepository {

    @Autowired
    private PricePlanMapper pricePlanMapper;
    @Autowired
    private PriceTierMapper priceTierMapper;
    @Autowired
    private DiscountRuleMapper discountRuleMapper;
    @Autowired
    private DomainEventPublisher eventPublisher;

    @Override
    public PricePlan findById(PricePlanId id) {
        PricePlanPO po = pricePlanMapper.selectById(id.getValue());
        if (po == null) {
            return null;
        }
        // 查询关联的价格档位和折扣规则
        List<PriceTierPO> tierPOs = priceTierMapper
            .selectByPlanId(id.getValue());
        List<DiscountRulePO> rulePOs = discountRuleMapper
            .selectByPlanId(id.getValue());
        // PO → 领域对象(聚合重建)
        return PricePlanConverter.toDomain(po, tierPOs, rulePOs);
    }

    @Override
    public void save(PricePlan pricePlan) {
        // 领域对象 → PO
        PricePlanPO po = PricePlanConverter.toPO(pricePlan);
        
        // 判断是新增还是更新
        if (pricePlanMapper.selectById(po.getId()) == null) {
            pricePlanMapper.insert(po);
        } else {
            pricePlanMapper.updateById(po);
        }

        // 保存子实体(简化:先删后插)
        priceTierMapper.deleteByPlanId(po.getId());
        for (PriceTier tier : pricePlan.getPriceTiers()) {
            priceTierMapper.insert(PricePlanConverter.toTierPO(
                tier, po.getId()));
        }

        // 发布领域事件
        pricePlan.getDomainEvents().forEach(eventPublisher::publish);
        pricePlan.clearDomainEvents();
    }
}

2.6 应用服务


/**
 * 定价应用服务
 * 职责:编排领域对象、事务管理、安全校验
 * 不包含业务逻辑(业务逻辑在领域层)
 */
@Service
@Slf4j
public class PricingApplicationService {

    private final PricePlanRepository pricePlanRepository;
    private final PricingDomainService pricingDomainService;

    public PricingApplicationService(
            PricePlanRepository pricePlanRepository,
            PricingDomainService pricingDomainService) {
        this.pricePlanRepository = pricePlanRepository;
        this.pricingDomainService = pricingDomainService;
    }

    /**
     * 计算价格(查询,不需要事务)
     */
    public PriceQueryResponse calculatePrice(PriceQueryRequest request) {
        log.info("计算价格: routeId={}, travelDate={}", 
            request.getRouteId(), request.getTravelDate());

        Money price = pricingDomainService.getBestPrice(
            request.getRouteId(),
            PriceType.valueOf(request.getPriceType()),
            LocalDateTime.parse(request.getTravelDate()),
            request.getQuantity(),
            MemberLevel.valueOf(request.getMemberLevel())
        );

        return PriceAssembler.toResponse(price);
    }

    /**
     * 创建定价方案(命令,需要事务)
     */
    @Transactional(rollbackFor = Exception.class)
    public PricePlanDTO createPricePlan(CreatePricePlanCommand command) {
        log.info("创建定价方案: {}", command.getPlanName());

        // 使用工厂方法创建聚合根
        PricePlan plan = PricePlan.create(
            command.getPlanName(),
            command.getRouteId(),
            PriceType.valueOf(command.getPriceType()),
            new DateRange(
                LocalDateTime.parse(command.getStartDate()),
                LocalDateTime.parse(command.getEndDate())
            )
        );

        // 添加价格档位
        command.getTiers().forEach(tierCmd -> {
            plan.addPriceTier(new PriceTier(
                new DateRange(
                    LocalDateTime.parse(tierCmd.getStartDate()),
                    LocalDateTime.parse(tierCmd.getEndDate())),
                Money.of(tierCmd.getUnitPrice())
            ));
        });

        // 保存(仓储实现中会发布领域事件)
        pricePlanRepository.save(plan);

        return PriceAssembler.toDTO(plan);
    }
}

2.7 接口层


@RestController
@RequestMapping("/api/pricing")
public class PricingController {

    private final PricingApplicationService pricingAppService;

    public PricingController(PricingApplicationService pricingAppService) {
        this.pricingAppService = pricingAppService;
    }

    @PostMapping("/calculate")
    public Result<PriceQueryResponse> calculatePrice(
            @RequestBody @Valid PriceQueryRequest request) {
        return Result.success(pricingAppService.calculatePrice(request));
    }

    @PostMapping("/plans")
    public Result<PricePlanDTO> createPlan(
            @RequestBody @Valid CreatePricePlanCommand command) {
        return Result.success(pricingAppService.createPricePlan(command));
    }
}

三、面试模拟篇(20%)

Q1:DDD和MVC的区别?

回答要点:

维度MVCDDD
核心关注点数据流转业务建模
模型特征贫血模型充血模型
代码组织按技术分层按业务域划分
业务逻辑位置Service层领域模型(聚合根/实体)
Service职责包含所有逻辑仅编排,不含业务规则
适用场景CRUD为主的简单系统业务复杂的系统
学习成本低高

一句话:MVC是按技术分(Controller/Service/DAO),DDD是按业务分(订单域/定价域/库存域)。

Q2:什么时候该用DDD?

适用场景:

不适用场景:

务实建议:不一定要全量DDD,可以局部采用。核心域用DDD,支撑域用传统方式。

Q3:聚合根的设计原则?

1. 小聚合:聚合越小越好,减少事务范围和并发冲突

2. 通过ID引用:聚合间通过ID引用而非直接持有对象

3. 一次事务只修改一个聚合:需要跨聚合时使用领域事件

4. 最终一致性:聚合间通过领域事件保证最终一致


四、练习篇(10%)

练习1:订单聚合根设计

为订单上下文设计完整的聚合根。


要求:
1. Order聚合根包含OrderItem实体
2. 实现:创建订单、添加商品、移除商品、取消订单、支付
3. 定义OrderStatus状态机(单向流转)
4. 定义领域事件:OrderCreatedEvent、OrderPaidEvent、OrderCancelledEvent

练习2:领域事件集成

实现跨限界上下文的领域事件通信。


// 提示:
// 1. 定义DomainEvent基类
// 2. 实现Spring Event Bus或MQ的事件发布
// 3. 订单上下文发布OrderCreatedEvent
// 4. 库存上下文监听并锁定库存

练习3:CQRS实现

为定价系统实现CQRS:写操作走数据库,读操作走Redis。


要求:
1. Command端:修改价格方案 → 写DB → 发布事件
2. Query端:监听事件 → 更新Redis缓存 → 查询走Redis
3. 保证最终一致性

DDD落地关键原则

原则说明
统一语言开发和业务用同一套术语
小聚合聚合尽量小,减少锁粒度
通过ID引用聚合间不直接引用对象
最终一致性聚合间通过事件同步
领域事件跨聚合、跨上下文通信
仓储隔离领域层不依赖具体技术

上一篇:P4-04-Spring-Cloud-Alibaba全家桶实战
下一篇:P4-06-系统设计面试题精讲