职责链模式(Chain of Responsibility Pattern):避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止
以学校的采购审批为例说明:花费在5000以下时有教学主任处理,5000到10000时由院长处理,大于10000时由校长审批
public class PurchaseRequest { /** 采购编号 */ private Integer id; /** 采购目的 */ private String purpose; /** 采购金额 */ private Double amount; public PurchaseRequest(Integer id, String purpose, Double amount) { this.id = id; this.purpose = purpose; this.amount = amount; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPurpose() { return purpose; } public void setPurpose(String purpose) { this.purpose = purpose; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } }
public abstract class Approver { /** 下一个处理者 */ Approver approver; /** 名字 */ String name; public Approver(String name) { this.name = name; } /** * 设置下一个审批者 * @param approver */ public void setApprover(Approver approver) { this.approver = approver; } /** * 具体处理由子类完成 * @param purchaseRequest */ protected abstract void processRequest(PurchaseRequest purchaseRequest); }
public class DepartmentApprover extends Approver { public DepartmentApprover(String name) { super(name); } @Override protected void processRequest(PurchaseRequest purchaseRequest) { if (purchaseRequest.getAmount() <= 5000) { System.out.println(" 采购项目 " + purchaseRequest.getPurpose() + " 被 " + this.name + " 处理"); } else { approver.processRequest(purchaseRequest); } } }
public class CollegeApprover extends Approver { public CollegeApprover(String name) { super(name); } @Override protected void processRequest(PurchaseRequest purchaseRequest) { if (purchaseRequest.getAmount() > 5000 && purchaseRequest.getAmount() <= 10000) { System.out.println(" 采购项目 " + purchaseRequest.getPurpose() + " 被 " + this.name + " 处理"); } else { approver.processRequest(purchaseRequest); } } }
public class SchoolMasterApprover extends Approver { public SchoolMasterApprover(String name) { super(name); } @Override protected void processRequest(PurchaseRequest purchaseRequest) { if (purchaseRequest.getAmount() > 10000) { System.out.println(" 采购项目 " + purchaseRequest.getPurpose() + " 被 " + this.name + " 处理"); } else { approver.processRequest(purchaseRequest); } } }
public class Demo01Test { public static void main(String[] args) { PurchaseRequest purchaseRequest = new PurchaseRequest(1, "采购电脑", 15000.0); DepartmentApprover departmentApprover = new DepartmentApprover("教学主任"); CollegeApprover collegeApprover = new CollegeApprover("学院院长"); SchoolMasterApprover schoolMasterApprover = new SchoolMasterApprover("校长"); departmentApprover.setApprover(collegeApprover); collegeApprover.setApprover(schoolMasterApprover); schoolMasterApprover.setApprover(departmentApprover); departmentApprover.processRequest(purchaseRequest); /** * 采购项目 采购电脑 被 校长 处理 */ } }
优点
缺点
适用场景