一天一个设计模式---责任链模式

责任链模式

简介

将不同职责的步骤进行串联,前一个执行完成之后才可以执行下一个,即前一个的责任完成之后会将这个责任给到下一个。

组成结构

一共有两个主要的类

  • 抽象的处理类(Handle),封装了每一个职责处理请求的方法和下一步处理的处理器。
  • 具体的处理类(ConcreteHandler),对应抽象类的实现,实际处理请求并将责任传递到下一个。

实现方式

JS 复制代码
class Handle {
  constructor () {
    this.handled = false
  }
  setNext (handle) {
    this.next = handle
    return this.next
  }
  deal (ctx) {
    // do something whit ctx
    if (!this.handled && this.next) {
      this.next.deal(ctx)
    }
    return true
  }
}

class HandleA extends Handle {
  deal (ctx) {
    // do something whit ctx
    ctx.handleA = true
    if (!this.handled && this.next) {
      this.next.deal(ctx)
    }
    return true
  }
}

class HandleB extends Handle {
  deal (ctx) {
    // do something whit ctx
    ctx.handleB = true
    if (!this.handled && this.next) {
      this.next.deal(ctx)
    }
    return true
  }
}

class HandleC extends Handle {
  deal (ctx) {
    // do something whit ctx
    ctx.handleC = true
    if (!this.handled && this.next) {
      this.next.deal(ctx)
    }
    return true
  }
}

const handlea = new HandleA()
handlea
  .setNext(new HandleB())
  .setNext(new HandleC())

const ctx = {}
handlea.deal(ctx)
console.log(ctx); // { handleA: true, handleB: true, handleC: true }

可以看到,由handled来决定是否在当前处理节点终止,否则就会一直按照设置的链路往下执行,这就是责任链的意义,你可以把他应用于:http请求的处理,审批的设计实现等等。。。

相关推荐
大辉狼_音频架构8 小时前
Vol.01 高频设计模式
设计模式
我登哥MVP15 小时前
走进 Gang of Four 设计模式:代理模式
设计模式·代理模式
我登哥MVP15 小时前
走进 Gang of Four 设计模式:外观模式
java·设计模式·外观模式
wuqingshun3141591 天前
什么是责任链模式,一般用在什么场景?
java·责任链模式
ttod_qzstudio1 天前
【软考设计模式】备忘录模式:对象状态的捕获与无损恢复精讲
设计模式·备忘录模式
ttod_qzstudio1 天前
【软考设计模式】责任链模式:请求传递的多级处理与发送接收解耦精讲
设计模式·责任链模式
2501_914245931 天前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
CaffeinePro1 天前
四⼤极简架构原则KISS/DRY/YAGNI/LOD
设计模式·架构
霸道流氓气质1 天前
SpringBoot中设计模式组合使用示例-策略、模板、观察者、门面、工厂、单例。
spring boot·后端·设计模式
ttod_qzstudio1 天前
【软考设计模式】观察者模式:一对多依赖的自动通知与订阅解耦精讲
观察者模式·设计模式