当前位置: 首页> 娱乐> 明星 > 设计模式之责任链模式

设计模式之责任链模式

时间:2025/7/18 2:47:06来源:https://blog.csdn.net/2301_76862031/article/details/141760704 浏览次数:0次

1.责任链概念

        允许请求沿着处理者链传递,直到链上的某个处理者决定处理此请求。通过这种方式,请求的发送者无须知道是哪一个接收者处理其请求,这使得系统可以动态地重新组织和分配责任。

2.责任链组成

        抽象处理者(Handler): 定义一个处理请求的接口,并持有下一个处理者的引用。

        具体处理者(Concrete Handlers): 实现抽象处理者的接口,在处理请求前判断自己是否能够处理该请求,如果可以则进行处理,否则将请求传递给下一个处理者。

        客户端(Client): 创建处理者链并将请求发送到链的第一个节点。

3.举个栗子:

以学生请假为例

7天        正常流程:老师(小于2天)==>领导(7天以下)===>校长(所有都行)    结果==》导员批

7天        非正常流程(导员有事): 老师(小于2天)===>校长(所有都行)              结果==》校长批

15天       正常流程:老师(小于2天)==>领导(7天以下)===>校长(所有都行)   结果==》校长批

4.代码实现

1)抽象处理者

package org.xiji.ChainOfResponsibility;/*** 抽象处理者*/
public abstract class Handler {/*** 下一个处理者*/protected Handler nextHandler;public Handler setNextHandler(Handler nextHandler) {this.nextHandler = nextHandler;return this.nextHandler;}/*** 定义处理方法*/public abstract void handle(int day);}

2)具体处理者

老师

package org.xiji.ChainOfResponsibility;/*** 老师*/
public class Teacher extends Handler{@Overridepublic void handle(int day) {if (day <= 2) {System.out.println("老师批注请假"+day+"天");}else {nextHandler.handle(day);}}
}

导员

package org.xiji.ChainOfResponsibility;/*** 导员*/
public class Instructor extends Handler{@Overridepublic void handle(int day) {if (day <= 7) {System.out.println("导员批注请假"+day+"天");} else {nextHandler.handle(day);}}
}

校长

package org.xiji.ChainOfResponsibility;/*** 校长*/
public class Principal extends Handler{@Overridepublic void handle(int day) {System.out.println("校长批注请假"+day+"天");}
}

3)客户端类

package org.xiji.ChainOfResponsibility;/*** 处理器测试类*/
public class ChainOfResponsibilityMain {public static void main(String[] args) {//老师角色Teacher teacher = new Teacher();//导员角色Instructor instructor = new Instructor();//校长角色Principal principal = new Principal();System.out.println("===========================");/*** 请假关系   老师==>导员===>校长*/System.out.println("正常流程请7天假");teacher.setNextHandler(instructor);instructor.setNextHandler(principal);//例如找老师请假七天int day = 7;teacher.handle(day);System.out.println("===========================");System.out.println("非正常流程请7天假");//找老师请假七天,导员不在,老师让你找校长/*** 请假关系 老师===>校长*/teacher.setNextHandler(principal);teacher.handle(day);System.out.println("===========================");System.out.println("正常流程请15天假");//想请15天假int day2 = 15;//正常流程 找老师请假===>导员===>校长teacher.setNextHandler(instructor);instructor.setNextHandler(principal);teacher.handle(day2);}
}

5.运行结果

关键字:设计模式之责任链模式

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: