责任链模式(Chain of Responsibility) Java

来源:互联网 发布:linux 永久关闭 swap 编辑:程序博客网 时间:2024/05/18 02:40


职责链模式(Chain of Responsibility)定义:

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



类结构图:




代码


Handler

package ding.study.designpatterns.chainofresponsibility;public abstract class Handler {/** * 责任链下一个继承者 */protected Handler successor;public void setHandler(Handler successor){this.successor=successor;}/** * 调用请求 * @author daniel * @time 2016-6-2 上午9:53:43 * @param request */public abstract void handlerRequest(int request);}

 


HandlerImpl1责任链小于10处理类

package ding.study.designpatterns.chainofresponsibility;/** * 责任链小于10处理类 *  * @author daniel * @email 576699909@qq.com * @time 2016-6-2 上午9:55:12 */public class HandlerImpl1 extends Handler {@Overridepublic void handlerRequest(int request) {if (request >= 0 && request < 10) {System.out.println("责任链小于10处理类处理");} else if (this.successor != null) {//交于下一个责任链执行this.successor.handlerRequest(request);}}}


HandlerImpl2

package ding.study.designpatterns.chainofresponsibility;/** * 责任链小于20大于10处理类 *  * @author daniel * @email 576699909@qq.com * @time 2016-6-2 上午9:55:12 */public class HandlerImpl2 extends Handler {@Overridepublic void handlerRequest(int request) {if (request >= 10 && request < 20) {System.out.println(" 责任链小于20大于10处理类");} else if (this.successor != null) {//交于下一个责任链执行this.successor.handlerRequest(request);}}}


HandlerImpl3

package ding.study.designpatterns.chainofresponsibility;/** * 大于等于20的处理类 * @author daniel * @email 576699909@qq.com * @time 2016-6-2 上午9:57:49 */public class HandlerImpl3 extends Handler {@Overridepublic void handlerRequest(int request) {if (request >= 20 ) {System.out.println("  大于等于20的处理类 处理");} else if (this.successor != null) {//交于下一个责任链执行this.successor.handlerRequest(request);}}}

Zmaiin

package ding.study.designpatterns.chainofresponsibility;/** * 职责链模式(Chain of Responsibility)定义:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。数字:1用-责任链小于10处理类处理数字:5用-责任链小于10处理类处理数字:11用- 责任链小于20大于10处理类数字:21用-  大于等于20的处理类 处理数字:20用-  大于等于20的处理类 处理数字:9999用-  大于等于20的处理类 处理 * @author daniel * @email 576699909@qq.com * @time 2016-6-2 上午10:04:43 */public class Zmain {/** * @author daniel * @time 2016-6-2 上午9:58:42 * @param args */public static void main(String[] args) {HandlerImpl1 handler1=new HandlerImpl1();HandlerImpl2 handler2=new HandlerImpl2();HandlerImpl3 handler3=new HandlerImpl3();        handler1.setHandler(handler2);        handler2.setHandler(handler3);        int[] request={1,5,11,21,20,9999};for(int i:request){System.out.print("数字:"+i+"用-");handler1.handlerRequest(i);}}}



输出结果



源代码:


https://github.com/dingsai88/StudyTest/tree/master/src/ding/study/designpatterns/chainofresponsibility
























0 0
原创粉丝点击