本文主要是介绍二十、职责链模式 chains of responsibility,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、定义
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
二、结构图
三、代码示例
1、测试代码Action.java
/*** 职责链模测试* @author lattice**/
public class Action {public static void main(String[] args) {Handler h1=new ConcreteHandler1();Handler h2=new ConcreteHandler2();Handler h3=new ConcreteHandler3();h1.setSuccoessor(h2);h2.setSuccoessor(h3);int [] requests={1,4,7,11,15,22,28,29};for(int sb:requests){h1.handleRequest(sb);}}}
2、职责链请求处理类代码Handler.java
/*** @use 测试职责链模式* @author lattice* @date 2017-01-09*/
public abstract class Handler {protected Handler successor;public void setSuccoessor(Handler successor){this.successor=successor;}public abstract void handleRequest(int request);
}class ConcreteHandler1 extends Handler{@Overridepublic void handleRequest(int request) {if(request>=0 &&request < 10){System.out.println(this.getClass().getName()+"处理请求"+request);}else if(successor != null){successor.handleRequest(request);}}}class ConcreteHandler2 extends Handler{@Overridepublic void handleRequest(int request) {if(request>=10 &&request < 20){System.out.println(this.getClass().getName()+"处理请求"+request);}else if(successor != null){successor.handleRequest(request);}}}class ConcreteHandler3 extends Handler{@Overridepublic void handleRequest(int request) {if(request>=20 &&request < 30){System.out.println(this.getClass().getName()+"处理请求"+request);}else if(successor != null){successor.handleRequest(request);}}}
这篇关于二十、职责链模式 chains of responsibility的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!