定义
将能够处理同一类请求的对象连成一条链,所提交的请求沿着链传递,链上的对象逐个判断是否有能力处理该请求,如果能则处理,如果不能则传递给链上的下一个对象处理。
场景举例
员工请假流程。
具体实现
请假申请基本信息类:
/**
* 封装请假的基本信息
*/
public class LeaveRequest {
// 员工名称
private String empName;
// 请假天数
private int leaveDays;
// 请假原因
private String reason;
public LeaveRequest(String empName, int leaveDays, String reason) {
this.empName = empName;
this.leaveDays = leaveDays;
this.reason = reason;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getLeaveDays() {
return leaveDays;
}
public void setLeaveDays(int leaveDays) {
this.leaveDays = leaveDays;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
}
定义抽象业务处理类Leader
/**
* 抽象业务处理类
*/
public abstract class Leader {
// 领导姓名
protected String name;
// 下一个处理的领导
protected Leader nextLeader; //责任链上的后继对象
public Leader(String name) {
this.name = name;
}
//设定责任链上的后继对象
public void setNextLeader(Leader nextLeader) {
this.nextLeader = nextLeader;
}
/**
* 处理请求的核心的业务方法
* @param request
*/
public abstract void handleRequest(LeaveRequest request);
}
定义业务处理类Director(主管)、Manager(经理)、Boss(老板),均继承于Leader。
Director
public class Director extends Leader {
public Director(String name) {
super(name);
}
@Override
public void handleRequest(LeaveRequest request) {
// 可以审批三天以内的申请
if (request.getLeaveDays() < 3) {
System.out.println("主管" + this.name + ":审批通过!");
} else {
if (this.nextLeader != null) {
System.out.println("主管" + this.name + ":超过三天,交给下一级领导审批!");
this.nextLeader.handleRequest(request);
}
}
}
}
Manager
public class Manager extends Leader {
public Manager(String name) {
super(name);
}
@Override
public void handleRequest(LeaveRequest request) {
// 可以审批十天以内的申请
if (request.getLeaveDays() < 10) {
System.out.println("经理" + this.name + ":审批通过!");
} else {
if (this.nextLeader != null) {
System.out.println("经理" + this.name + ":超过十天,交给下一级领导审批!");
this.nextLeader.handleRequest(request);
}
}
}
}
Boss
public class Boss extends Leader {
public Boss(String name) {
super(name);
}
@Override
public void handleRequest(LeaveRequest request) {
if (request.getLeaveDays() < 30) {
System.out.println("老板" + this.name + ":审批通过!");
} else {
System.out.println("莫非" + request.getEmpName() + "想辞职,居然请假" + request.getLeaveDays() + "天!");
}
}
}
测试类
public class Test {
public static void main(String[] args) {
// 定义业务处理类
Leader a = new Director("张三");
Leader b = new Manager("李四");
Leader c = new Boss("王总");
// 组织责任链对象的关系
a.setNextLeader(b);
b.setNextLeader(c);
// 开始请假操作
LeaveRequest request = new LeaveRequest("小明", 20, "老婆生孩子回家探望!");
System.out.println("员工" + request.getEmpName() + ":请假天数:" + request.getLeaveDays() + ",理由:" + request.getReason());
a.handleRequest(request);
}
}
结果打印:
责任链模式总结
- 所有责任链实现类有统一的抽象(抽象类或接口),实现统一的业务处理方法,并维护下一节点的引用。
- 责任链节点不关心节点的执行顺序,该顺序由主流程在初始化时确定,实现节点间的解耦。
- 请求者无需知道请求具体会被哪个节点处理,总之最终会被处理就对了,实现请求者与处理者之间的解耦。
来源:CSDN
作者:KeepMoving++
链接:https://blog.csdn.net/u011212394/article/details/104108940