zhangdizhangdi

职责链模式 ⭐

定义

责任链模式(Chain of Responsibility Pattern),使多个对象都有机会处理请求,从而避免了请求的发送者与多个接收者直接的耦合关系,将这些接收者连接成一条链,顺着这条链传递该请求,直到找到能处理该请求的对象。

实现

js
class Request {
  constructor(amount) {
    this.amount = amount
    console.log(`Amount: ¥${amount}`)
  }
  get(count) {
    this.amount -= count
    console.log(`Get: ¥${count}, Amount: ¥${this.amount}`)
    return this
  }
}

const request = new Request(378)
request.get(100).get(50).get(20).get(10).get(5).get(1)
执行结果
Amount: ¥378
Get: ¥100, Amount: ¥278
Get: ¥50, Amount: ¥228
Get: ¥20, Amount: ¥208
Get: ¥10, Amount: ¥198
Get: ¥5, Amount: ¥193
Get: ¥1, Amount: ¥192

应用场景

  • jQuery 链式
  • promise 链式

参考