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

责任链模式

简介

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

组成结构

一共有两个主要的类

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

相关推荐
吃饺子不吃馅41 分钟前
面试官:JWT、Cookie、Session、Token有什么区别?
前端·设计模式·面试
leafff1232 小时前
一文读懂:如何选择适合的RAG系统架构设计模式?
设计模式·自然语言处理·系统架构
ZHE|张恒4 小时前
设计模式实战篇(一):彻底搞懂 Singleton 单例模式
单例模式·设计模式
喝拿铁写前端18 小时前
从面条代码到抽象能力:一个小表单场景里的前端成长四阶段
前端·设计模式·架构
依米_18 小时前
一文带你剖析 Promise.then all 实现原理,状态机、发布订阅模式完美实现异步编程
javascript·设计模式
jzhwolp19 小时前
从基本链表到侵入式链表,体会内核设计思路
c语言·后端·设计模式
李宥小哥1 天前
结构型设计模式1
设计模式
lapiii3581 天前
[智能体设计模式] 第五章 :函数调用
microsoft·设计模式
lapiii3581 天前
[智能体设计模式] 第 1 章:提示链(Prompt Chaining)
设计模式·prompt
昨天的猫1 天前
《拒绝重复代码!模板模式教你优雅复用算法骨架》
后端·设计模式