在公司负责的就是订单取消业务,老系统中各种类型订单取消都是通过if else 判断不同的订单类型进行不同的逻辑。在经历老系统的折磨和产品需求的不断变更,决定进行一次大的重构:消灭 if else。
接下来就向大家介绍下是如何消灭 if else。
1. if else模式
@Service public class CancelOrderService { public void process(OrderDTO orderDTO) { int serviceType = orderDTO.getServiceType(); if (1 == serviceType) { System.out.println("取消即时订单"); } else if (2 == serviceType) { System.out.println("取消预约订单"); } else if (3 == serviceType) { System.out.println("取消拼车订单"); } } }
若干个月再来看就是这样的感觉
2. 策略模式
2.1 策略模式实现的Service
@Service public class CancelOrderStrategyService { @Autowired private StrategyContext context; public void process(OrderDTO orderDTO) { OrderTypeEnum orderTypeEnum = OrderTypeEnum.getByCode(orderDTO.getServiceType()); AbstractStrategy strategy = context.getStrategy(orderTypeEnum); strategy.process(orderDTO); } }
简洁的有点过分了是不是!!!
2.2 各种类型策略实现及抽象策略类
下面选取了即时订单和预约订单的策略.
@Service @OrderTypeAnnotation(orderType = OrderTypeEnum.INSTANT) public class InstantOrderStrategy extends AbstractStrategy { @Override public void process(OrderDTO orderDTO) { System.out.println("取消即时订单"); } }
@Service @OrderTypeAnnotation(orderType = OrderTypeEnum.BOOKING) public class BookingOrderStrategy extends AbstractStrategy { @Override public void process(OrderDTO orderDTO) { System.out.println("取消预约订单"); } }
public abstract class