责任链模式在JavaScript中通过动态组装处理器实现多级审批流解耦——每个处理器决定是否处理请求或传递给下一级,基类统一接口,子类专注自身权限逻辑。

责任链模式在 JavaScript 中处理多级审批流非常自然——核心是让每个审批节点(Handler)决定自己是否处理请求,或把请求“往下传”。关键不在于硬编码流程顺序,而在于动态组装、解耦判断逻辑和跳过无关环节。
定义抽象处理器基类
所有审批节点都继承同一个基类,统一接口,确保可串联:
class ApprovalHandler {
constructor(next = null) {
this.next = next; // 指向下一级处理器
}
handle(request) {
// 子类必须实现具体审批逻辑
if (typeof this.process === 'function') {
const result = this.process(request);
if (result !== undefined) return result; // 显式返回表示已终结
}
// 未终结则委托给下一级
return this.next ? this.next.handle(request) : '审批流结束,无处理器响应';
}
}
实现具体审批角色(如组长 → 部门经理 → CTO)
每个角色只关注自己的权限范围,不关心上下游是谁。例如:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
class TeamLeadHandler extends ApprovalHandler {
process(request) {
if (request.amount <= 5000 && request.department === 'frontend') {
return { approved: true, by: 'TeamLead', note: '额度内,前端组可批' };
}
}
}
class DeptManagerHandler extends ApprovalHandler {
process(request) {
if (request.amount <= 20000) {
return { approved: true, by: 'DeptManager', note: '部门额度内通过' };
}
}
}
class CTOHandler extends ApprovalHandler {
process(request) {
if (request.isStrategic || request.amount > 20000) {
return { approved: true, by: 'CTO', note: '战略项目,CTO终审通过' };
}
}
}
动态组装审批链并触发
链的顺序即审批层级,支持运行时调整(比如临时加 VP 审核),也支持跳过某级(如小额直接由组长终审):
立即学习“Java免费学习笔记(深入)”;
// 构建链:组长 → 部门经理 → CTO
const chain = new TeamLeadHandler(
new DeptManagerHandler(
new CTOHandler()
)
);
// 发起审批
const result = chain.handle({
amount: 15000,
department: 'backend',
isStrategic: false
});
console.log(result);
// → { approved: true, by: 'DeptManager', note: '部门额度内通过' }
增强实用性的小技巧
-
支持中断与日志:在基类
handle中加入console.log(`→ ${this.constructor.name}`),方便追踪流转路径 -
允许条件跳转:某个 handler 可根据结果主动调用
this.next?.next?.handle(...)跳过中间环节(如紧急流程直送 CTO) -
返回结构化响应:统一返回
{ approved, by, note, next?: Handler },便于上层做 UI 渲染或重试控制 - 链的复用与分支:不同业务线可共用 DeptManagerHandler,只需拼接不同前后节点


















