责任链模式
责任链模式是一种处理请求的模式,它让多个处理器都有机会处理该请求,直到其中某个处理成功为止,责任链模式把多个处理器串成链,然后让请求在链上传递。
案例
一个请假条,如果只是1-3条,是由组长来审批;
如果是4-10天,由经理来处理;
如果是10天以上,由老板来处理
代码
/**
* 请假处理人抽象类
*/
public abstract class Process {
private Process nextProcess;
private Integer startDay;
private Integer endDay;
/**
* 构造函数确定责任范围
* @param startDay
* @param endDay
*/
public Process(Integer startDay, Integer endDay) {
this.startDay = startDay;
this.endDay = endDay;
}
public Process getNextProcess() {
return nextProcess;
}
/**
* 设置责任链
*
* @param nextProcess
*/
public void setNextProcess(Process nextProcess) {
this.nextProcess = nextProcess;
}
/**
* 精髓
* 采用类似于链表的方式,通过递归,知道找到相应的角色
*
* @param leave
*/
public final void submit(Leave leave) {
Integer day = leave.getDay();
if (day <= endDay && day >= startDay) {
handle();
} else if (nextProcess != null) {
nextProcess.submit(leave);
} else {
System.out.println("无人处理");
}
}
/**
* 由子类来实现
*/
public abstract void handle();
}
组长
public class GroupLeader extends Process {
public GroupLeader() {
super(1, 3);
}
@Override
public void handle() {
System.out.println("小组长");
}
}
client
public class Client {
public static void main(String[] args) {
//创建角色
Process boss = new Boss();
Process groupLeader = new GroupLeader();
Process manager = new Manager();
//确定责任链
groupLeader.setNextProcess(manager);
manager.setNextProcess(boss);
Leave leave = new Leave(9, "xxx");
groupLeader.submit(leave);
}
}
参考
https://www.cnblogs.com/fengyumeng/p/10839570.html