职责链模式(Chain of Responsibility Pattern)
|
1 2 3 |
定义:为请求创建了一个接收者对象的链。 目的:避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。 场景:红楼梦中的"击鼓传花"。 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
class Approver { constructor(name, limit) { this.name = name this.limit = limit this.next = null } processRequest(request) { // 自己能处理,就处理并结束 if (request.amount < this.limit) { console.log(`${this.name}批准采购:${request.productName}`) return } // 自己不能处理,交给下一级 if (this.next) { return this.next.processRequest(request) } // 已经到达链尾,仍然无法处理 console.log(`采购金额超出审批权限:${request.productName}`) } } // 创建审批者 const manager = new Approver('经理', 10000) const vicePresident = new Approver('副总', 25000) const president = new Approver('总经理', 100000) // 连接职责链:经理 → 副总 → 总经理 manager.next = vicePresident vicePresident.next = president // 所有请求都从链头提交 manager.processRequest({ amount: 4000, productName: '电话' }) manager.processRequest({ amount: 10000, productName: '软件' }) manager.processRequest({ amount: 40000, productName: '电脑' }) manager.processRequest({ amount: 200000, productName: '服务器' }) |
输出:
经理批准采购:电话
副总批准采购:软件
总经理批准采购:电脑
采购金额超出审批权限:服务器

