美文网首页
行为型模式 --- 责任链模式

行为型模式 --- 责任链模式

作者: 十二找十三 | 来源:发表于2020-08-24 20:31 被阅读0次
    package study.org;
    
    public class Demo {
        public static void main(String[] args) {
            // 组装责任链
            Handler handler1 = new ConcreteHandler1();
            Handler handler2 = new ConcreteHandler2();
            Handler handler3 = new ConcreteHandler3();
            handler2.setNext(handler3);
            handler1.setNext(handler2);
            
            // 提交请求
            handler1.operation("ConcreteHandler2");
        }
    }
    
    abstract class Handler {
        private Handler next;
    
        public Handler getNext() {
            return next;
        }
    
        public void setNext(Handler next) {
            this.next = next;
        }
    
        abstract void operation(String tail);
    }
    
    class ConcreteHandler1 extends Handler {
    
        @Override
        void operation(String tail) {
            if ("ConcreteHandler1".equals(tail)) {
                System.out.println("ConcreteHandler1 finish");
            } else {
                if (null != getNext()) {
                    System.out.println("ConcreteHandler1 next->");
                    getNext().operation(tail);
                } else {
                    System.out.println("ConcreteHandler1 nothing! or error");
                }
            }
        }
    }
    
    class ConcreteHandler2 extends Handler {
    
        @Override
        void operation(String tail) {
            if ("ConcreteHandler2".equals(tail)) {
                System.out.println("ConcreteHandler2 finish");
            } else {
                if (null != getNext()) {
                    System.out.println("ConcreteHandler2 next->");
                    getNext().operation(tail);
                } else {
                    System.out.println("ConcreteHandler2 nothing! or error");
                }
            }
        }
    }
    
    class ConcreteHandler3 extends Handler {
    
        @Override
        void operation(String tail) {
            if ("ConcreteHandler3".equals(tail)) {
                System.out.println("ConcreteHandler3 finish");
            } else {
                if (null != getNext()) {
                    System.out.println("ConcreteHandler3 next->");
                    getNext().operation(tail);
                } else {
                    System.out.println("ConcreteHandler3 nothing! or error");
                }
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:行为型模式 --- 责任链模式

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