标签:xtend stat 职责链 灵活 否则 解耦 super tor 审批
采购审批项目:如果金额小于等于 5000,由教学主任审批; 金额小于等于 10000,由院长审批;金额 小于等于 30000,由副校长审批;金额超过 30000 以上,由校长审批。
//请求类
public class PurchaseRequest {
private int type = 0; //请求类型
private float price = 0.0f; //请求金额
private int id = 0;
//构造器
public PurchaseRequest(int type, float price, int id) {
this.type = type;
this.price = price;
this.id = id;
}
public int getType() {
return type;
}
public float getPrice() {
return price;
}
public int getId() {
return id;
}
}
// 抽象的处理者
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);
}
// 具体的处理者 : 系主任
// 其他具体的处理者类似,只不过是判断范围改变
// 院长 purchaseRequest.getPrice() < 5000 && purchaseRequest.getPrice() <= 10000
// 副校长 purchaseRequest.getPrice() < 10000 && purchaseRequest.getPrice() <= 30000
// 校长 purchaseRequest.getPrice() > 30000
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 Client {
public static void main(String[] args) {
//创建一个请求
PurchaseRequest purchaseRequest = new PurchaseRequest(1, 31000, 1);
//创建相关的审批人
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);
viceSchoolMasterApprover.processRequest(purchaseRequest);
}
}
SpringMVC-HandlerExecutionChain 类使用到了职责链模式
标签:xtend stat 职责链 灵活 否则 解耦 super tor 审批
原文地址:https://www.cnblogs.com/Songzw/p/13121969.html