|
|
/**
|
|
|
* 订单处理器类,负责处理订单的主要逻辑
|
|
|
*/
|
|
|
package com.orderprocessing;
|
|
|
|
|
|
import com.orderprocessing.Logger;
|
|
|
import com.orderprocessing.OrderValidator;
|
|
|
import com.orderprocessing.OrderNotifier;
|
|
|
import com.orderprocessing.DiscountStrategy;
|
|
|
|
|
|
public class OrderProcessor {
|
|
|
private OrderValidator validator;
|
|
|
private OrderNotifier notifier;
|
|
|
private Logger logger;
|
|
|
private DiscountStrategy discountStrategy;
|
|
|
|
|
|
/**
|
|
|
* 构造方法,注入依赖
|
|
|
* @param validator 订单验证器
|
|
|
* @param notifier 订单通知器
|
|
|
* @param logger 日志记录器
|
|
|
*/
|
|
|
public OrderProcessor(OrderValidator validator, OrderNotifier notifier, Logger logger) {
|
|
|
this.validator = validator;
|
|
|
this.notifier = notifier;
|
|
|
this.logger = logger;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 设置折扣策略
|
|
|
* @param discountStrategy 折扣策略
|
|
|
*/
|
|
|
public void setDiscountStrategy(DiscountStrategy discountStrategy) {
|
|
|
this.discountStrategy = discountStrategy;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 验证订单
|
|
|
* @param order 需要验证的订单
|
|
|
* @return 如果验证通过返回true,否则返回false
|
|
|
*/
|
|
|
public boolean validateOrder(Order order) {
|
|
|
logger.log("开始验证订单: " + order.getOrderId());
|
|
|
|
|
|
boolean isValid = validator.isValid(order);
|
|
|
|
|
|
if (isValid) {
|
|
|
order.setStatus(Order.OrderStatus.VALIDATED);
|
|
|
logger.log("订单验证通过: " + order.getOrderId());
|
|
|
} else {
|
|
|
logger.log("订单验证失败: " + order.getOrderId());
|
|
|
// 记录详细错误信息
|
|
|
for (String error : validator.getValidationErrors(order)) {
|
|
|
logger.log("验证错误: " + error);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return isValid;
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 处理订单
|
|
|
* @param order 需要处理的订单
|
|
|
* @return 如果处理成功返回true,否则返回false
|
|
|
*/
|
|
|
public boolean processOrder(Order order) {
|
|
|
logger.log("开始处理订单: " + order.getOrderId());
|
|
|
|
|
|
// 首先验证订单
|
|
|
if (!validateOrder(order)) {
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 应用折扣
|
|
|
if (discountStrategy != null) {
|
|
|
double discount = discountStrategy.calculateDiscount(order);
|
|
|
order.applyDiscount(discount);
|
|
|
logger.log("应用折扣: " + discount + " 到订单: " + order.getOrderId());
|
|
|
}
|
|
|
|
|
|
// 更新订单状态
|
|
|
order.setStatus(Order.OrderStatus.PROCESSED);
|
|
|
logger.log("订单处理完成: " + order.getOrderId() + ", 最终金额: " + order.getTotalAmount());
|
|
|
|
|
|
// 发送通知
|
|
|
notifier.notifyOrderProcessed(order);
|
|
|
|
|
|
return true;
|
|
|
}
|
|
|
} |