责任链模式(Chain of Responsibility Pattern)又名职责链模式,为了避免请求发送者与多个请求处理者耦合在一起,将所有请求的处理者通过前一对象记住其下一个对象的引用而连成一条链;当有请求发生时,可将请求沿着这条链传递,直到有对象处理它为止。
职责链模式主要包含以下角色:
【案例】
现需要开发一个请假流程控制系统。请假一天以下的假只需要小组长同意即可;请假1天到3天的假还需要部门经理同意;请求3天到7天还需要总经理同意才行。
public class Client {
public static void main(String[] args) {
//请假条
LeaveRequest leave = new LeaveRequest("小花",5,"身体不适");
//创建各位各位领导
GroupLeader groupLeader = new GroupLeader();
Manager manager = new Manager();
GeneralManager generalManager = new GeneralManager();
groupLeader.setNextHandler(manager);//小组长的领导是部门经理
manager.setNextHandler(generalManager);//部门经理的领导是总经理
//提交申请
groupLeader.submit(leave);
}
}
//请假条类
class LeaveRequest{
private String name;//姓名
private int num;//请假天数
private String content;//请假内容
public LeaveRequest(String name, int num, String content) {
this.name = name;
this.num = num;
this.content = content;
}
/* getter and setter */
}
abstract class Handler{
//该领导能处理的请假天数区间
private int numStart;
private int numEnd;
//领导上面的领导
private Handler nextHandler;
//设置请假天数范围 上不封顶
public Handler(int numStart) {
this.numStart = numStart;
}
//设置请假天数范围
public Handler(int numStart, int numEnd) {
this.numStart = numStart;
this.numEnd = numEnd;
}
//设置上级领导
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
//提交请假条
public final void submit(LeaveRequest leave) {
if (0 == this.numStart) {
return;
}
//如果请假天数达到该领导者的处理要求
if (leave.getNum() >= this.numStart) {
this.handleLeave(leave);
//如果还有上级 并且请假天数超过了当前领导的处理范围
if (null != this.nextHandler && leave.getNum() > numEnd) {
this.nextHandler.submit(leave);//继续提交
} else {
System.out.println("流程结束");
}
}
}
//各级领导处理请假条方法
protected abstract void handleLeave(LeaveRequest leave);
}
//小组长
class GroupLeader extends Handler{
public GroupLeader(){
super(1,3);
}
protected void handleLeave(LeaveRequest leave){
System.out.println(leave.getName() + "请假" + leave.getNum() +"天," + leave.getContent() + "。");
System.out.println("小组长审批:同意");
}
}
//部门经理
class Manager extends Handler{
public Manager(){
super(3,7);
}
protected void handleLeave(LeaveRequest leave){
System.out.println(leave.getName() + "请假" + leave.getNum() +"天," + leave.getContent() + "。");
System.out.println("部门经理审批:同意");
}
}
//总经理
class GeneralManager extends Handler{
public GeneralManager(){
super(7);
}
protected void handleLeave(LeaveRequest leave){
System.out.println(leave.getName() + "请假" + leave.getNum() +"天," + leave.getContent() + "。");
System.out.println("总经理审批:同意");
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/m0_60117382/article/details/123720182
内容来源于网络,如有侵权,请联系作者删除!