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

责任链模式

简介

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

组成结构

一共有两个主要的类

  • 抽象的处理类(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请求的处理,审批的设计实现等等。。。

相关推荐
wy_hhxx32 分钟前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥1 小时前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
用户624293196621 天前
告别 Electron 臃肿与 Wireshark 老化界面:用 Rust + Tauri 2.0 构建多总线网络与现场总线深度分析仪 Omni-Probe
设计模式
是2的10次方啊1 天前
设计模式与生活㉒:暖气热不热,得一间一间摸过去
设计模式
bigbread1 天前
迭代器模式-在区域健康档案导出中的实战应用
设计模式
装不满的克莱因瓶1 天前
设计模式之策略模式核心概念和应用场景
java·后端·设计模式·架构·系统架构·策略模式
是2的10次方啊2 天前
设计模式与生活㉑:一句“建议复查”,是好几句话拼出来的
设计模式
杯子不吃紫菜3 天前
LangGraph 体系实战(下):中断恢复、流式、子图与设计模式
单片机·嵌入式硬件·设计模式
是2的10次方啊3 天前
设计模式与生活⑳:楼里的事都找前台,你就再没见过师傅
设计模式
是2的10次方啊4 天前
设计模式与生活⑲:投影连不上,别急着换投影仪
设计模式