美文网首页
Java设计模式--责任链模式

Java设计模式--责任链模式

作者: 留给时光吧 | 来源:发表于2018-04-19 22:26 被阅读0次

    该模式将多个接收者连成链,当请求来临时,沿着责任链匹配接受者,直到有对象接受为止,对请求者和接收者进行了充分的解耦。简单实现:

    抽象类:

    public abstract class Handler {
        public Handler next;
    
        public abstract void handleRequest(String condition);
    
        public void setNext(Handler handler){
            next = handler;
        };
    }
    

    实现类

    public class HandlerImpl1 extends Handler{
        public static final String CONDITION = "HandlerImpl1";
    
        @Override
        public void handleRequest(String condition) {
            if (CONDITION.equals(condition)){
                System.out.println("HandlerImpl1 handle");
            }else{
                if(next != null)
                    next.handleRequest(condition);
            }
        }
    }
    
    public class HandlerImpl2 extends Handler{
        public static final String CONDITION = "HandlerImpl2";
    
        @Override
        public void handleRequest(String condition) {
            if (CONDITION.equals(condition)){
                System.out.println("HandlerImpl2 handle");
            }else{
                if(next != null)
                    next.handleRequest(condition);
            }
        }
    }
    
    public class HandlerImpl3 extends Handler{
        public static final String CONDITION = "HandlerImpl3";
    
        @Override
        public void handleRequest(String condition) {
            if (CONDITION.equals(condition)){
                System.out.println("HandlerImpl3 handle");
            }else{
                if(next != null)
                    next.handleRequest(condition);
            }
        }
    }
    

    测试类·

    public class test {
    
        public static void main(String[] args) {
            HandlerImpl1 handlerImpl1 = new HandlerImpl1();
            HandlerImpl2 handlerImpl2 = new HandlerImpl2();
            HandlerImpl3 handlerImpl3 = new HandlerImpl3();
            handlerImpl1.setNext(handlerImpl2);
            handlerImpl2.setNext(handlerImpl3);
    
            handlerImpl1.handleRequest("HandlerImpl2");
        }
    
    }
    

    相关文章

      网友评论

          本文标题:Java设计模式--责任链模式

          本文链接:https://www.haomeiwen.com/subject/ebegkftx.html