4.10、完整Domain实现示例
分类: DDD领域驱动设计实战
完整 Domain 实现示例
本节将通过完整的订单领域实现示例,展示如何应用 DDD 设计原则。本节将学习完整的订单领域实现。
本节将学习:订单聚合根实现、订单项值对象、订单领域服务,以及订单仓储实现。
订单聚合根实现
Order 实体
package com.example.ecommerce.domain.model; import java.util.ArrayList; import java.util.List; public class Order { private Long id; private String orderNo; private Long userId; private Money totalAmount; private OrderStatus status; private ShippingAddress shippingAddress; private List<OrderItem> items = new ArrayList<>(); private List<DomainEvent> domainEvents = new ArrayList<>(); public void addItem(OrderItem item) { this.items.add(item); calculateTotal(); } public void calculateTotal() { Money total = Money.ZERO; for (OrderItem item : items) { total = total.add(item.getSubtotal()); } this.totalAmount = total; } public void create() { this.status = OrderStatus.PENDING; this.domainEvents.add(new OrderCreatedEvent(this.id, this.userId, this.totalAmount)); } }
订单项值对象
OrderItem 实体
package com.example.ecommerce.domain.model; public class OrderItem { private Long id; private Long productId; private Integer quantity; private Money price; private Money subtotal; public OrderItem(Long productId, Integer quantity, Money price) { this.productId = productId; this.quantity = quantity; this.price = price; this.subtotal = price.multiply(quantity); } }
订单领域服务
OrderDomainService
package com.example.ecommerce.domain.service; import com.example.ecommerce.domain.model.Order; import org.springframework.stereotype.Service; @Service public class OrderDomainService { public void validateOrder(Order order) { if (order.getItems().isEmpty()) { throw new BusinessException("Order must have at least one item"); } if (order.getTotalAmount().isNegative()) { throw new BusinessException("Order total cannot be negative"); } } }
订单仓储实现
OrderRepository
package com.example.ecommerce.domain.repository; import com.example.ecommerce.domain.model.Order; import java.util.Optional; public interface OrderRepository { void save(Order order); Optional<Order> findById(Long id); Optional<Order> findByOrderNo(String orderNo); }
官方资源
- DDD 完整示例:https://www.domainlanguage.com/ddd/
本节小结
在本节中,我们学习了:
第一个是订单聚合根实现。 完整的订单聚合根实现。
第二个是订单项值对象。 订单项实体设计。
第三个是订单领域服务。 订单领域服务实现。
第四个是订单仓储实现。 订单仓储接口设计。
这就是完整的 Domain 实现示例。通过这个示例,我们可以看到 DDD 设计的完整应用。
在下一节,我们将学习 DDD 项目结构重构。