1.请求类:
java
// 请求类,用于表示报销请求
class ReimbursementRequest {
private String employeeName; // 员工姓名
private double amount; // 报销金额
// 构造函数,初始化员工姓名和报销金额
public ReimbursementRequest(String employeeName, double amount) {
this.employeeName = employeeName;
this.amount = amount;
}
// 获取员工姓名
public String getEmployeeName() {
return employeeName;
}
// 获取报销金额
public double getAmount() {
return amount;
}
}
2.处理接口:
java
// 处理器接口,定义处理请求的方法和设置下一个处理器的方法
interface ApprovalHandler {
void handleRequest(ReimbursementRequest request); // 处理请求的方法
void setNextHandler(ApprovalHandler handler); // 设置下一个处理器的方法
}
3.具体处理器实现类-主管,CFO:
java
// 具体处理器实现类 - 主管
class Director implements ApprovalHandler {
private ApprovalHandler nextHandler; // 下一个处理器
@Override
public void handleRequest(ReimbursementRequest request) {
if (request.getAmount() <= 5000) {
System.out.println("Director approved the reimbursement request for " + request.getEmployeeName());
} else if (nextHandler != null) {
nextHandler.handleRequest(request); // 传递请求给下一个处理器
}
}
@Override
public void setNextHandler(ApprovalHandler handler) {
this.nextHandler = handler; // 设置下一个处理器
}
}
// 具体处理器实现类 - CFO
class CFO implements ApprovalHandler {
private ApprovalHandler nextHandler; // 下一个处理器
@Override
public void handleRequest(ReimbursementRequest request) {
if (request.getAmount() > 5000) {
System.out.println("CFO approved the reimbursement request for " + request.getEmployeeName());
} else {
System.out.println("Request denied for " + request.getEmployeeName());
}
}
@Override
public void setNextHandler(ApprovalHandler handler) {
this.nextHandler = handler; // 设置下一个处理器
}
}
4.主程序类:
java
// 主程序类,演示责任链模式的应用
public class ReimbursementApprovalSystem {
public static void main(String[] args) {
// 创建处理器对象
ApprovalHandler manager = new Manager();
ApprovalHandler director = new Director();
ApprovalHandler cfo = new CFO();
// 构建责任链
manager.setNextHandler(director);
director.setNextHandler(cfo);
// 发起报销请求
ReimbursementRequest request1 = new ReimbursementRequest("Alice", 800);
manager.handleRequest(request1);
ReimbursementRequest request2 = new ReimbursementRequest("Bob", 4500);
manager.handleRequest(request2);
ReimbursementRequest request3 = new ReimbursementRequest("Charlie", 10000);
manager.handleRequest(request3);
}
}