责任链模式(Chain of Responsibility),一种行为型设计模式,它为请求创建了一个接收者对象的链。这种模式给予了请求的处理更多的灵活性,可以动态地决定请求由哪个对象来处理。实际上,每个接收者对象都包含对另一个接收者对象的引用,如果当前对象无法处理请求,它会将请求传递给下一个接收者对象。
主要角色:
例如:员工请假,请假2天内,经理审批;超过2天,不大于5天,总监审批;超过5天,CTO审批。
public class LeaveRequest {
private int days;
public LeaveRequest(int days) {
this.days = days;
}
public int getDays() {
return days;
}
}
public interface LeaveRequestHandler {
void setNextHandler(LeaveRequestHandler nextHandler);
void handleRequest(LeaveRequest request);
}
@Slf4j
public class Manager implements LeaveRequestHandler {
private LeaveRequestHandler nextHandler;
@Override
public void setNextHandler(LeaveRequestHandler nextHandler) {
this.nextHandler = nextHandler;
}
@Override
public void handleRequest(LeaveRequest request) {
if (request.getDays() <= 2) {
log.info("审批流程处理 -> 经理");
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}
@Slf4j
public class Commissioner implements LeaveRequestHandler {
private LeaveRequestHandler nextHandler;
@Override
public void setNextHandler(LeaveRequestHandler nextHandler) {
this.nextHandler = nextHandler;
}
@Override
public void handleRequest(LeaveRequest request) {
if (request.getDays() <= 5) {
log.info("审批流程处理 -> 总监");
} else {
nextHandler.handleRequest(request);
}
}
}
@Slf4j
public class CTO implements LeaveRequestHandler {
private LeaveRequestHandler nextHandler;
@Override
public void setNextHandler(LeaveRequestHandler nextHandler) {
this.nextHandler = nextHandler;
}
@Override
public void handleRequest(LeaveRequest request) {
if (request.getDays() > 5) {
log.info("审批流程处理 -> CTO");
} else {
log.info("没有流程节点");
}
}
}
@Slf4j
public class Client {
public static void main(String[] args) {
LeaveRequestHandler manager = new Manager();
LeaveRequestHandler commissioner = new Commissioner();
LeaveRequestHandler cto = new CTO();
manager.setNextHandler(commissioner);
commissioner.setNextHandler(cto);
log.info("请假10天");
LeaveRequest request = new LeaveRequest(10);
manager.handleRequest(request);
}
}
输出控制台:
请假10天
审批流程处理 -> CTO