蘇阿細 - 责任链模式
type: channel
link: https://www.wangchouchou.com/tag/%E8%B4%A3%E4%BB%BB%E9%93%BE%E6%A8%A1%E5%BC%8F/
items: 行为型模式-责任链模式

行为型模式-责任链模式
type: item
date: 2022-09-16T15:09:00+00:00
description: （1）概述为了避免请求发送者与多个请求处理者耦合在一起，将所有请求的处理者通过前一对象记住其下一个对象的引用而连城一条链；当有请求发生时，可将请求沿着这条链传递，只到有对象处理它为止（2）结构抽象处理者角色：定义处理请求的接口，包含抽象处理方法和一个后继链接具体处理者角色：实现抽象处理者的处理方法，判断能否处理本次请求，如果可以处理则处理，否则将该请求转发给后继者客户类角色：创建处理链，并向链头的具体处理者对象提交请求，它不关心处理细节及请求传递的过程（3）案例以请假为例抽象处理者角色public abstract class Handler { protected final static int ONE = 1; protected final static int THREE = 3; protected final static int SEVEN = 7; //不同角色可以处理的请假天数区间 private int startNum; private int endNum; //声明后继者（该案例中的上级领导） private Handler nextHandler; public Handler(int startNum) { this.startNum = startNum; } public Handler(int startNum, int endNum) { this.startNum = startNum; this.endNum = endNum; } /** * 设置上级领导对象 * * @param nextHandler */ public void setNextHandler(Handler nextHandler) { this.nextHandler = nextHandler; } /** * 各级领导处理请假条的方法 * * @param leave */ protected abstract void handlerLeave(LeaveRequest leave); /** * 提交请假申请 * * @param leave */ public final void submit(LeaveRequest leave) { //当前领导审批 this.handlerLeave(leave); //上级领导审批 if (this.nextHandler != null && leave.getNum() > this.endNum) { this.nextHandler.handlerLeave(leave); } else { System.out.println("流程结束"); } } }具体处理者角色public class GroupLeader extends Handler { public GroupLeader() { super(0, Handler.ONE); } @Override protected void handlerLeave(LeaveRequest leave) { System.out.println(leave.getName() + "由于" + leave.getContent() + "，请假：" + leave.getNum() + "天"); System.out.println("组长审批意见：同意"); } } public class Manager extends Handler { public Manager() { super(Handler.ONE, Handler.THREE); } @Override protected void handlerLeave(LeaveRequest leave) { System.out.println(leave.getName() + "由于" + leave.getContent() + "，请假：" + leave.getNum() + "天"); System.out.println("部门经理意见：同意"); } } public class GeneralManager extends Handler { public GeneralManager() { super(Handler.THREE, Handler.SEVEN); } @Override protected void handlerLeave(LeaveRequest leave) { System.out.println(leave.getName() + "由于" + leave.getContent() + "，请假：" + leave.getNum() + "天"); System.out.p…