• 责任链模式实战


    责任链模式实战

    第一步:设置参数dto

    /**
    * 请求DTO
    */
    public class RequestDTO {

    }

    第二步:设置父类handler

    public abstract class ParentHandler {
    protected ParentHandler nextHandler;

    protected ApplicationContext context = SpringContextUtil.getApplicationContext();

    protected abstract boolean needHandler(RequestDTO request);

    /**
    * 子类handler需重写该handler()方法
    * @param request
    */
    protected void handler(RequestDTO request){
    ParentHandler handler =this.nextHandler;
    while (handler !=null){
    if(handler.needHandler(request)){
    handler.handler(request);
    }
    handler =handler.nextHandler;
    }
    }
    /**
    * 设置nextHandler
    * @param nextHandler
    * @return
    */
    protected ParentHandler setNextHandler(ParentHandler nextHandler){
    this.nextHandler =nextHandler;
    return this.nextHandler;
    }
    }

    第三步:设置子类handler

    第一个子类handler

    public class FirstHandler extends ParentHandler{
    @Override
    protected boolean needHandler(RequestDTO request) {
    return true;
    }

    @Override
    protected void handler(RequestDTO request){
    System.out.println("FirstHandler.handler");
    //此处只有在firstHandler中添加,其他的子类handler不能添加
    super.handler(request);
    }
    }

    第二个子类handler

    public class SecondHandler extends ParentHandler {
    @Override
    protected boolean needHandler(RequestDTO request) {
    return true;
    }

    @Override
    protected void handler(RequestDTO request){
    System.out.println("SecondHandler.handler");
    }
    }

    第三个子类handler

    public class ThirdHandler extends ParentHandler {
    @Override
    protected boolean needHandler(RequestDTO request) {
    return true;
    }

    @Override
    protected void handler(RequestDTO request){
    System.out.println("ThirdHandler.handler");
    }
    }

    子类handler按需添加 。。。。。

    第四步:设置handler工厂类,main方法测试

    public class HandlerFactroy {
    private static ParentHandler handlerLinked =new FirstHandler();
    static {
    handlerLinked
    .setNextHandler(new SecondHandler())
    .setNextHandler(new ThirdHandler());
    }

    public static ParentHandler getHandlerLinked(){
    return handlerLinked;
    }

    public static void main(String[] args){
    RequestDTO requestDTO =new RequestDTO();
    HandlerFactroy.getHandlerLinked().handler(requestDTO);
    }

    }




  • 相关阅读:
    在HttpHandlers (ASHX files)中使用Session
    EventCalendar控件源码和ASP.NET 2.0 Beta 2 Starter Kits中可能遇到的问题
    C# 获取数据库中某个某个表的创建脚本[原创]
    Linq 合并多个查询条件
    自定义WCF RIA Services 超时时间
    也来学学插件式开发续利用MEF
    HTML5程序设计 Geolocation API
    反射实体模型生成Oracle SQL脚本
    Entity Framework With Oracle
    Entity Framework Code First在Oracle下的伪实现
  • 原文地址:https://www.cnblogs.com/wenhuang/p/9896497.html
Copyright © 2020-2023  润新知