责任链模式(Chain of Responsibility Pattern)是一种经典的行为型设计模式,它通过将多个处理对象连接成一条链,使请求沿链传递直至被处理。该模式完美解耦了请求发送者与接收者,让多个对象都有机会处理请求。
结构解析
责任链模式包含三个核心组件:抽象处理器(Handler)、具体处理器(ConcreteHandler) 和客户端(Client)。每个处理器保存后继处理器引用,形成处理链。
实战示例:请假审批流程
// 抽象处理器
public abstract class ApprovalHandler {
protected ApprovalHandler nextHandler;
public void setNextHandler(ApprovalHandler nextHandler) {
this.nextHandler = nextHandler;
}
public abstract void processRequest(LeaveRequest request);
}
// 具体处理器:项目经理
public class ProjectManager extends ApprovalHandler {
@Override
public void processRequest(LeaveRequest request) {
if (request.getDays() <= 3) {
System.out.println("项目经理批准" + request.getDays() + "天请假");
} else if (nextHandler != null) {
nextHandler.processRequest(request);
}
}
}
// 具体处理器:部门经理
public class DepartmentManager extends ApprovalHandler {
@Override
public void processRequest(LeaveRequest request) {
if (request.getDays() <= 7) {
System.out.println("部门经理批准" + request.getDays() + "天请假");
} else if (nextHandler != null) {
nextHandler.processRequest(request);
}
}
}
// 客户端构建处理链
public class Client {
public static void main(String[] args) {
ApprovalHandler pm = new ProjectManager();
ApprovalHandler dm = new DepartmentManager();
pm.setNextHandler(dm);
// 发送请求
pm.processRequest(new LeaveRequest(5));
}
}
责任链模式在Java生态中广泛应用,如Servlet过滤器、Spring Security安全拦截链等。它提供了优秀的扩展性和灵活性,但需要警惕链过长带来的性能问题。
通过合理运用责任链模式,开发者可以构建出高度解耦、易于扩展的处理流程,真正实现"各司其职"的优雅设计。
1144

被折叠的 条评论
为什么被折叠?



