一步操作可能分为 多个职责角色 来完成,把这些角色都分开,然后 用一个链串起来,将 发起者 和 各个处理者 进行隔离;
适用场景:一个 请求 的处理,需要 多个对象 中的 一个或若干个对象 协作进行处理;
优点:
- 解耦:请求的 发送者 和 接收者 解耦; 接收者 是 请求的处理者;
- 动态组合:责任链 可以 动态组合,使用配置 设置责任链 的顺序及 是否出现;可以随时对责任链排序,随时增加拆除责任链中的某个请求对象;
缺点:
- 性能:如果 责任链 太长,或责任链中请求的 处理时间过长,可能会 影响性能;
- 个数:责任链 可能过多;
类图
代码
class Employee {
constructor(next) {
this.next = next;
}
}
class GroupLeader extends Employee {
audit() {
console.log('组长已经审批!');
this.next && this.next.audit();
}
}
class Manager extends Employee {
audit() {
console.log('经理已经审批!');
this.next && this.next.audit();
}
}
class Boss extends Employee {
audit() {
console.log('老板已经审批!');
this.next && this.next.audit();
}
}
let boss = new Boss();
let manager = new Manager(boss);
let groupLeader = new GroupLeader(manager);
groupLeader.audit();
模版方法模式
上一篇