一、核心作用:
处理同一类请求的对象连成一条链,所提交的请求沿着链传递,链上的对象逐个判断是否有能力处理请求,如果能则处理,如果不能则传递给链上的下一个对象
二、常见应用场景:
1、审批
2、开发场景:try-catch
三、责任链模式的实现:
LeaveRequest:员工提交请求类
Leader:抽象的请假责任处理类
Director:处理类
四、代码示例:
一、员工提交请求类:
package com.hezeu.chainOfResp;
/**
* @Classname LeaveRequest
* @Description TODO
* @Date 2020/2/25 下午 04:53
* @Created by 朱进博 1724282894@qq.com
*/
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;
}
}
二、抽象请假责任处理类:
package com.hezeu.chainOfResp;
/**
* @Classname Leader
* @Description TODO
* @Date 2020/2/25 下午 04:55
* @Created by 朱进博 1724282894@qq.com
*/
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;
}
public abstract void hanleRequest(LeaveRequest request);
}
三、处理类:
package com.hezeu.chainOfResp;
/**
* @Classname Director
* @Description TODO
* @Date 2020/2/25 下午 04:58
* @Created by 朱进博 1724282894@qq.com
*/
public class Director extends Leader {
public Director(String name){
super(name);
}
@Override
public void hanleRequest(LeaveRequest request) {
if(request.getLeaveDays()<3){
System.out.println("员工:"+request.getEmpName()+"请假,天数"+request.getLeaveDays()+
"理由:"+request.getReason());
System.out.println("主任"+this.name+"审批通过");
}else{
if(this.nextLeader!=null)
{
this.nextLeader.hanleRequest(request);
}
}
}
}
四、测试类
package com.hezeu.chainOfResp;
/**
* @Classname Client
* @Description TODO
* @Date 2020/2/25 下午 05:17
* @Created by 朱进博 1724282894@qq.com
*/
public class Client {
public static void main(String[] args) {
Leader a = new Director("主任1");
Leader b = new Director("经理2");
Leader c = new GeneralManager("总经理");
a.setNextLeader(b);
b.setNextLeader(c);
LeaveRequest req1 = new LeaveRequest("Tom",10,"探亲");
a.hanleRequest(req1);
}
}
结果如下:
五、责任链模式的优缺点:
优点:
- 责任分离处理,各节点各司其职
- 责任链一般用于处理流程节点之类的业务场景
- 请求者无需知道哪个对象去处理
- 由于责任链的创建完全在客户端,因此新增具体处理者对原有类库没有影响,只需添加新的类,然后再客户端调用时添加即可,符合开闭原则
缺点:
- 性能问题,一个请求有可能从头到尾,责任链比较长,调试能有麻烦