概念:使多个对象都有机会处理请求,从而避免了请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。最匹配的场景应该就是逐层审批的模式。
责任链模式只有两个角色,一个抽象处理类,一个具体处理类。这个模式的关键在于多个处理类层层持有,形成一个链条,并各自处理职责内的请求。
下面以一个请假审批的例子,帮助大家理解该模式。
public abstract class Approver {
protected Approver nextApprover;
public void setNextApprover(Approver nextApprover) {
this.nextApprover = nextApprover;
}
public abstract void processRequest(LeaveRequest request);
}
public class TeamLead extends Approver {
@Override
public void processRequest(LeaveRequest request) {
if (request.getDays() <= 2) {
System.out.println("团队领导审批 " + request.getDays() + " 天假.");
} else if (nextApprover != null) {
System.out.println("发送上级经理审批。");
nextApprover.processRequest(request);
} else {
System.out.println("超出团队领导审批权限。");
}
}
}
public class Manager extends Approver {
@Override
public void processRequest(LeaveRequest request) {
if (request.getDays() <= 5) {
System.out.println("经理审批 " + request.getDays() + " 天假.");
} else if (nextApprover != null) {
System.out.println("发送总监审批");
nextApprover.processRequest(request);
} else {
System.out.println("超出经理审批范围");
}
}
}
public class Director extends Approver {
@Override
public void processRequest(LeaveRequest request) {
if (request.getDays() <= 10) {
System.out.println("总监审批 " + request.getDays() + " 天假.");
} else {
System.out.println("超出总监审批范围。");
}
}
}
public class LeaveRequest {
private String employeeName;
private int days;
public LeaveRequest(String employeeName, int days) {
this.employeeName = employeeName;
this.days = days;
}
public String getEmployeeName() {
return employeeName;
}
public int getDays() {
return days;
}
}
public class Demo {
public static void main(String[] args) {
TeamLead teamLead = new TeamLead();
Manager manager = new Manager();
Director director = new Director();
teamLead.setNextApprover(manager);
manager.setNextApprover(director);
LeaveRequest request1 = new LeaveRequest("天哥", 2);
LeaveRequest request2 = new LeaveRequest("天哥", 5);
LeaveRequest request3 = new LeaveRequest("天哥", 10);
LeaveRequest request4 = new LeaveRequest("天哥", 15);
teamLead.processRequest(request1);
System.out.println("**************************分割线*************************************");
teamLead.processRequest(request2);
System.out.println("**************************分割线*************************************");
teamLead.processRequest(request3);
System.out.println("**************************分割线*************************************");
teamLead.processRequest(request4);
}
}
如果大家需要视频版本的讲解,欢迎大家关注我的B站。
十五、设计模式之命令模式讲解