策略模式
在业务系统中,可能根据某个值的不同,进行不同的逻辑代码,如下:
public void process(OrderDto orderDto){ int type = orderDto.getType(); if (1==type){ System.out.println("取消即时订单"); }else if (2==type){ System.out.println("取消预约订单"); } }
若干个月再来看可能就有点看不懂了。
此时我们采用策略模式
1、定义抽象类
public abstract class AbstractStrategy { abstract public void process(OrderDto orderDto); }
2、根据不同的类型,实现具体的业务代码
public class InstantOrderStrategy extends AbstractStrategy{ private static volatile InstantOrderStrategy instantOrderStrategy = null; @Override public void process(OrderDto orderDto) {
//具体的业务代码。。。。。。 System.out.println(orderDto.getDesc()); } /** * 单例模式 * @return */ public static InstantOrderStrategy getInstance(){ if (null==instantOrderStrategy){ synchronized (InstantOrderStrategy.class){ if (null==instantOrderStrategy){ instantOrderStrategy = new InstantOrderStrategy(); } } } return instantOrderStrategy; }
3、定义枚举类,列举类型
public enum OrderTypeEnum { INSTANT(1,"取消及时订单", InstantOrderStrategy.getInstance()), BOOKING(2,"取消预约订单", BookingOrderStrategy.getInstance()), ; private final Integer code; private final String desc; private final AbstractStrategy abstractStrategy; OrderTypeEnum(Integer code, String desc,AbstractStrategy abstractStrategy) { this.code = code; this.desc = desc; this.abstractStrategy = abstractStrategy; } public static OrderTypeEnum valueOf(Integer code){ for (OrderTypeEnum orderTypeEnum : OrderTypeEnum.values()) { if (orderTypeEnum.code.equals(code)){ return orderTypeEnum; } } return null; } public Integer getCode() { return code; } public String getDesc() { return desc; } public AbstractStrategy getAbstractStrategy() { return abstractStrategy; }
4、调用代码
public class CancelOrderStrategyService { public void cancelOrder(OrderDto orderDto) throws IllegalAccessException, InstantiationException {
//根据type获取指定的业务处理类 AbstractStrategy abstractStrategy = OrderTypeEnum.valueOf(orderDto.getType()).getAbstractStrategy(); abstractStrategy.process(orderDto); } }