目录
一:定义
职责链模式通常每个接收者都包含对另一个接收者的引用,如果一个对象不能处理该请求,那么他会把相同的请求传给下一个接收者,以此类推
Handler:抽象的处理者,定义了一个处理请求的接口,同时含有另外Handler
ConcreteHandlerA,B:是具体的处理者,处理他自己负责的请求,他可以访问后继者(即下一个处理者)
Request:含有很多属性表示一个请求
二:案例
public abstract class Approver { Approver approver;// 下一个处理者 String name;// 名字 public Approver(String name) { this.name = name; } // 下一个处理者 public void setApprover(Approver approver) { this.approver = approver; } // 处理审批请求的方法,得到一个请求,处理是子类完成,因此该方法做成抽象 public abstract void processRequest(PurchaseRequest purchaseRequest); }
public class CollegeApprover extends Approver{ public CollegeApprover(String name) { super(name); } @Override public void processRequest(PurchaseRequest purchaseRequest) { if (purchaseRequest.getPrice() >= 5000 && purchaseRequest.getPrice() <= 10000) { System.out.println("请求编号id=" + purchaseRequest.getId() + " 被" + this.name + "处理"); } else { approver.processRequest(purchaseRequest); } } }
public class DepartmentApprover extends Approver{ public DepartmentApprover(String name) { super(name); } @Override public void processRequest(PurchaseRequest purchaseRequest) { if (purchaseRequest.getPrice() <= 5000) { System.out.println("请求编号id=" + purchaseRequest.getId() + " 被" + this.name + "处理"); } else { approver.processRequest(purchaseRequest); } } }
public class SchoolMasterApprover extends Approver{ public SchoolMasterApprover(String name) { super(name); } @Override public void processRequest(PurchaseRequest purchaseRequest) { if (purchaseRequest.getPrice() >= 30000) { System.out.println("请求编号id=" + purchaseRequest.getId() + " 被" + this.name + "处理"); } else { approver.processRequest(purchaseRequest); } } }
public class ViceSchoolMasterApprover extends Approver{ public ViceSchoolMasterApprover(String name) { super(name); } @Override public void processRequest(PurchaseRequest purchaseRequest) { if (purchaseRequest.getPrice() >= 10000 && purchaseRequest.getPrice() <= 30000) { System.out.println("请求编号id=" + purchaseRequest.getId() + " 被" + this.name + "处理"); } else { approver.processRequest(purchaseRequest); } } }
@Data @AllArgsConstructor @NoArgsConstructor public class PurchaseRequest { private int id; private int type;// 类型 private int num; private float price = 0.0f; }
// 客户端
public class Client {
public static void main(String[] args) {
// 创建一个请求
PurchaseRequest purchaseRequest = new PurchaseRequest(1, 1, 1, 31000f);
// 创建相关的审批人
DepartmentApprover departmentApprover = new DepartmentApprover("张主任");
CollegeApprover collegeApprover = new CollegeApprover("李院长");
ViceSchoolMasterApprover viceSchoolMasterApprover = new ViceSchoolMasterApprover("王副校长");
SchoolMasterApprover schoolMasterApprover = new SchoolMasterApprover("童校长");
// 需要将各个审批级别的下一个设置好(处理人构成环形)
departmentApprover.setApprover(collegeApprover);
collegeApprover.setApprover(viceSchoolMasterApprover);
viceSchoolMasterApprover.setApprover(schoolMasterApprover);
schoolMasterApprover.setApprover(departmentApprover);
// 请求处理
departmentApprover.processRequest(purchaseRequest);
}
}