职责链模式ChainOfResponsibility

原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11407114.html 

 

1.定义

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

 

2.结构图

 

Handler:定义职责的接口,通常在这里定义处理请求的方法,可以在这里实现后继链。
ConcreteHandler:实现职责的类,在这个类中,实现对在它职责范围内请求的处理,如果处理,就继续转发请求给后继者。
Client:职责链的客户端,向链上的具体处理对象提交请求,让职责链负责处理。

 

3.本质

职责链模式的本质:分离职责,动态组合。

 

4.Code Demo

Handler.java

 1 package org.fool.dp.cor;
 2 
 3 public abstract class Handler {
 4     protected Handler successor;
 5 
 6     public void setSuccessor(Handler successor) {
 7         this.successor = successor;
 8     }
 9 
10     public abstract void handleRequest();
11 }

ConcreteHandler1.java

 1 package org.fool.dp.cor;
 2 
 3 public class ConcreteHandler1 extends Handler {
 4     @Override
 5     public void handleRequest() {
 6         boolean someCondition = false;
 7 
 8         if (someCondition) {
 9             System.out.println("ConcreteHandler1 invoked...");
10         } else {
11             if (successor != null) {
12                 successor.handleRequest();
13             }
14         }
15     }
16 }

ConcreteHandler2.java

 1 package org.fool.dp.cor;
 2 
 3 public class ConcreteHandler2 extends Handler {
 4     @Override
 5     public void handleRequest() {
 6         boolean someCondition = false;
 7 
 8         if (someCondition) {
 9             System.out.println("ConcreteHandler2 invoked...");
10         } else {
11             if (successor != null) {
12                 successor.handleRequest();
13             }
14         }
15     }
16 }

ConcreteHandler3.java

 1 package org.fool.dp.cor;
 2 
 3 public class ConcreteHandler3 extends Handler {
 4     @Override
 5     public void handleRequest() {
 6         boolean someCondition = true;
 7 
 8         if (someCondition) {
 9             System.out.println("ConcreteHandler3 invoked...");
10         } else {
11             if (successor != null) {
12                 successor.handleRequest();
13             }
14         }
15     }
16 }

Client.java

 1 package org.fool.dp.cor;
 2 
 3 public class Client {
 4     public static void main(String[] args) {
 5         Handler handler1 = new ConcreteHandler1();
 6         Handler handler2 = new ConcreteHandler2();
 7         Handler handler3 = new ConcreteHandler3();
 8 
 9         handler1.setSuccessor(handler2);
10         handler2.setSuccessor(handler3);
11 
12         handler1.handleRequest();
13     }
14 }

 

posted @ 2019-08-25 10:29  李白与酒  阅读(229)  评论(0编辑  收藏  举报