【设计模式】Java 设计模式之责任链模式(Chain of Responsibility)
// 责任链模式示例:处理请假申请
// 请假类型枚举
enum LeaveType {
SICK_LEAVE, PARENTAL_LEAVE, VACATION_LEAVE
}
// 请假申请类
class LeaveRequest {
private LeaveType type;
private String reason;
// 构造函数、getter和setter省略
public LeaveType getType() {
return type;
}
public String getReason() {
return reason;
}
}
// 抽象处理者
abstract class Approver {
protected Approver nextApprover; // 下一个处理者
public void setNextApprover(Approver nextApprover) {
this.nextApprover = nextApprover;
}
public abstract void processRequest(LeaveRequest request);
}
// 具体处理者
class Director extends Approver {
@Override
public void processRequest(LeaveRequest request) {
if (request.getType() == LeaveType.SICK_LEAVE && request.getReason().length() < 50) {
System.out.println("Director approved the request.");
} else {
if (nextApprover != null) {
nextApprover.processRequest(request);
} else {
System.out.println("Request needs more details.");
}
}
}
}
// 客户端代码
public class ChainOfResponsibilityPatternExample {
public static void main(String[] args) {
Approver director = new Director();
Approver vicePresident = new VicePresident();
Approver president = new President();
// 设置责任链
director.setNextApprover(vicePresident);
vicePresident.setNextApprover(president);
// 创建一个请假申请
LeaveRequest sickLeave = new LeaveRequest();
sickLeave.setType(LeaveType.SICK_LEAVE);
sickLeave.setReason("Feeling sick");
// 处理请假申请
director.processRequest(sickLeave);
}
}
这个例子中,我们定义了一个请假类型的枚举LeaveType
和一个请假申请类LeaveRequest
。然后定义了一个抽象类Approver
作为处理者的基类,它包含了设置下一个处理者的方法和一个处理请假申请的抽象方法。接着,我们创建了具体的处理者类,如Director
、VicePresident
和President
,它们继承自Approver
并实现了处理请假的方法。最后,在客户端代码中,我们设置了责任链,并向第一个处理者提交了一个请假申请。
评论已关闭