Code refactoring of the strategy pattern

Background: The order system more and more bloated, along with changes in demand iteration, personnel, system maintenance costs getting higher and higher, just to have a way to increase demand is to cancel the order, it plans to gradually begin reconstruction code.

View the original code found there are many ways to cancel the order, the original practice is done by determining if-else, the drawbacks of this approach is obvious, each additional one way, you need to change the original code, the branch will be back more and more ... strategy mode is a good way to solve this problem. man of few words said, directly on the code (business code skip) 1. define an interface

public interface CancelOrderHandler {

    /**
     * 获取处理类型
     * @return
     */
    int getHandlerType();

    /**
     * 取消订单的处理
     */
    BizResponse<String> handler(OrderCancelDto dto);
}

复制代码

2. Write a class that implements the interface of the user cancels the order fulfillment

/**
 * 用户取消订单处理器
 */
@Service
@Slf4j
public class UserCancelOrderHandler implements CancelOrderHandler {
  
    /**
     * 获取处理类型
     *
     * @return
     */
    @Override
    public int getHandlerType() {
        return CancelOrderTypeEnum.USER.getType();
    }

    /**
     * 取消订单的处理
     */
    @Override
    public BizResponse<String> handler(OrderCancelDto dto) {
        log.info("用户取消订单...");
        //todo 业务代码
        return null;
    }
}

复制代码

Cancel the order fulfillment system

/**
 * 系统取消订单处理器
 */
@Service
@Slf4j
public class SystemCancelOrderHandler implements CancelOrderHandler {
  
    /**
     * 获取处理类型
     *
     * @return
     */
    @Override
    public int getHandlerType() {
        return CancelOrderTypeEnum.SYSTEM.getType();
    }

    /**
     * 取消订单的处理
     */
    @Override
    public BizResponse<String> handler(OrderCancelDto dto) {
        log.info("系统取消订单...");
        //todo 业务代码
        return null;
    }
}

复制代码

Here the interface and implementation are defined, we then define a policy class factory class.

/**
 * 取消订单的工厂类
 */
@Component
public class CancelHandlerFactory {
    
    @Autowired
    private List<CancelOrderHandler> handlerList;

    /**
     * 根据取消类型获取具体的实现
     * @param cancelType 取消订单类型
     * @return
     */
    public CancelOrderHandler getCancelHandler(Integer cancelType){
        return handlerList.stream().filter(handler -> handler.getHandlerType() == cancelType).findFirst().get();
    }

}

复制代码

Here is a tip

    @Autowired
    private List<CancelOrderHandler> handlerList; 
复制代码

So you can write notes using the spring @Autowired implementation of the interface automatically injected into the list or map, the back and then have a new way to cancel the order, simply write a new implementation class is OK, is not very convenient, code is also very clear!

Guess you like

Origin juejin.im/post/5e7c21f56fb9a009833586d1