Domain、BO、BIZ 三层的协作关系
电商、银行、医疗三个领域的经典分层案例,展示 domain
、bo
、biz
三层的协作关系:
案例1:电商订单系统
1. Domain层(领域模型)
// domain/entity/Order.java
public class Order {private String orderId;private List<OrderItem> items;private OrderStatus status;// 领域行为:计算订单总价public BigDecimal calculateTotal() {return items.stream().map(item -> item.getPrice().multiply(item.getQuantity())).reduce(BigDecimal.ZERO, BigDecimal::add);}
}
2. BO层(业务对象)
// bo/OrderBO.java
public class OrderBO {private Order order;private InventoryService inventoryService;// 业务逻辑:校验库存并预留public void reserveInventory() {if (!inventoryService.checkStock(order.getItems())) {throw new BusinessException("库存不足");}}
}
3. Biz层(业务服务)
// biz/OrderService.java
public class OrderService {public void createOrder(OrderCreateDTO dto) {OrderBO orderBO = new OrderBO(convertToOrder(dto));orderBO.reserveInventory(); // 调用BO处理业务规则paymentService.charge(orderBO.getOrder()); // 协调第三方支付}
}
案例2:银行转账系统
1. Domain层
// domain/entity/Account.java
public class Account {private String accountId;private BigDecimal balance;// 领域行为:扣款public void debit(BigDecimal amount) {if (balance.compareTo(amount) < 0) {throw new InsufficientBalanceException();}this.balance = balance.subtract(amount);}
}
2. BO层
// bo/TransferBO.java
public class TransferBO {private Account source;private Account target;// 业务逻辑:执行双账户原子操作public void executeTransfer(BigDecimal amount) {source.debit(amount);target.credit(amount); // 省略credit方法实现}
}
3. Biz层
// biz/TransferService.java
public class TransferService {@Transactionalpublic void transfer(TransferRequestDTO dto) {TransferBO transferBO = new TransferBO(accountRepository.findById(dto.getSourceAccountId()),accountRepository.findById(dto.getTargetAccountId()));transferBO.executeTransfer(dto.getAmount()); // 调用BOauditLog.logTransfer(dto); // 协调审计日志}
}
案例3:医院预约系统
1. Domain层
// domain/entity/Appointment.java
public class Appointment {private Doctor doctor;private Patient patient;private LocalDateTime time;// 领域规则:校验预约时间有效性public boolean isValidTime() {return time.getHour() >= 9 && time.getHour() <= 17;}
}
2. BO层
// bo/AppointmentBO.java
public class AppointmentBO {private Appointment appointment;private ScheduleService scheduleService;// 业务逻辑:检查医生排班冲突public void checkConflict() {if (!scheduleService.isAvailable(appointment.getDoctor(), appointment.getTime())) {throw new ConflictException("医生该时段已排班");}}
}
3. Biz层
// biz/AppointmentService.java
public class AppointmentService {public void bookAppointment(AppointmentDTO dto) {AppointmentBO appointmentBO = new AppointmentBO(convertToEntity(dto));appointmentBO.checkConflict(); // 调用BO校验notificationService.sendConfirmation(appointmentBO.getAppointment()); // 协调通知}
}
关键总结
- Domain层:纯业务实体和规则,与技术无关
- BO层:组合多个领域对象的业务场景逻辑
- Biz层:协调领域逻辑与技术实现(如数据库、API调用)
- 适用场景:复杂业务系统(如金融、电商、医疗),简单CRUD项目可合并BO和Biz层