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

责任链模式

简介

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

组成结构

一共有两个主要的类

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

相关推荐
AI人工智能+电脑小能手16 小时前
大白话说Java设计模式-45-解释器模式(源码剖析篇)
java·设计模式·解释器模式·源码分析·pattern·spel·javacc
码匠许师傅20 小时前
【设计模式精讲】4.单例模式(Singleton)
c++·单例模式·设计模式
雾削木20 小时前
2026 编程领域热点知识速览:AI 辅助开发、设计模式实战与嵌入式高效迭代
人工智能·设计模式
AI人工智能+电脑小能手2 天前
大白话说Java设计模式-42-访问者模式(业务实战篇)
java·spring·设计模式·访问者模式·asm·营销规则·数据结构与操作分离
AI人工智能+电脑小能手2 天前
大白话说Java设计模式-43-访问者模式(源码剖析篇)
java·设计模式·访问者模式·源码分析·elementvisitor·asm classvisitor·spring spel
Michael_lcf2 天前
Agent设计模式:思考-行动-观察循环的本质与局限
设计模式·agent设计模式·agent设计模式的本质
丰锋ff2 天前
设计模式学习笔记
笔记·学习·设计模式
米啦啦.3 天前
设计模式/
观察者模式·单例模式·设计模式·工厂模式
QuZhengRong3 天前
【AI】Agent 全栈进阶|Agent 设计模式
人工智能·学习·设计模式·llm·agent
码匠许师傅3 天前
【设计模式精讲】2. 设计原则基石:SOLID 与几条关键原则
java·设计模式·log4j