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{
- @Override
- public void handle(int day) {
- if (day <= 2) {
- System.out.println("老师批注请假"+day+"天");
- }else {
- nextHandler.handle(day);
- }
- }
- }
复制代码 导员
- package org.xiji.ChainOfResponsibility;
- /**
- * 导员
- */
- public class Instructor extends Handler{
- @Override
- public void handle(int day) {
- if (day <= 7) {
- System.out.println("导员批注请假"+day+"天");
- } else {
- nextHandler.handle(day);
- }
- }
- }
复制代码 校长
- package org.xiji.ChainOfResponsibility;
- /**
- * 校长
- */
- public class Principal extends Handler{
- @Override
- public 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.运行效果
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |