责任链模式-实践

抽象类

public abstract class AbstractHandler {

    private AbstractHandler nextHandler;

    public AbstractHandler getNextHandler() {
        return nextHandler;
    }

    public void setNextHandler(AbstractHandler nextHandler) {
        this.nextHandler = nextHandler;
    }

    public void filter(HttpServletRequest request, HttpServletResponse response) {
        doFilter(request, response);
        if (getNextHandler()!=null){
            getNextHandler().filter(request, response);
        }
    }

    abstract void doFilter(HttpServletRequest request, HttpServletResponse response);

}

责任链1

@Slf4j
@Order(1)
@Component
public class CheckParamFilter extends AbstractHandler {
    @Override
    void doFilter(HttpServletRequest request, HttpServletResponse response) {
        log.info("参数校验。。。");
    }
}

责任链2

@Component
@Order(2)
@Slf4j
public class CheckSecurityFilter extends AbstractHandler {
    @Override
    void doFilter(HttpServletRequest request, HttpServletResponse response) {
        log.info("安全验证。。。");
    }
}

测试

@Component
public class ChainPatternDemo {

    @Autowired
    private List<AbstractHandler> handlerList;

    private AbstractHandler abstractHandler;

    @PostConstruct
    public void initializeChainFilter(){
        for (int i = 0; i < handlerList.size(); i++) {
            if (i == 0){
                abstractHandler = handlerList.get(i);
            }else {
                AbstractHandler currentHandler = handlerList.get(i - 1);
                AbstractHandler nextHandler = handlerList.get(i);
                currentHandler.setNextHandler(nextHandler);
            }
        }
    }


    public HttpServletResponse exec(HttpServletRequest request, HttpServletResponse response){
        abstractHandler.filter(request, response);
        return response;
    }
}
posted @ 2022-10-18 15:27  紫川先生  阅读(16)  评论(0编辑  收藏  举报