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

责任链模式

简介

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

组成结构

一共有两个主要的类

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

相关推荐
cooldream20096 小时前
深入理解MVP架构:让UI层与业务逻辑完美分离的设计模式
ui·设计模式·架构·系统架构师
摘星编程9 小时前
并发设计模式实战系列(3):工作队列
设计模式·并发编程
Pasregret9 小时前
访问者模式:分离数据结构与操作的设计模式
数据结构·设计模式·访问者模式
Aniugel12 小时前
JavaScript高级面试题
javascript·设计模式·面试
不当菜虚困12 小时前
JAVA设计模式——(四)门面模式
java·开发语言·设计模式
Niuguangshuo12 小时前
Python设计模式:MVC模式
python·设计模式·mvc
Lei活在当下13 小时前
【现代 Android APP 架构】01. APP 架构综述
android·设计模式·架构
前端大白话13 小时前
震惊!90%前端工程师都踩过的坑!computed属性vs methods到底该怎么选?一文揭秘高效开发密码
前端·vue.js·设计模式
前端大白话13 小时前
前端必看!figure标签在响应式图片排版中的王炸操作,grid/flex布局实战指南
前端·设计模式·html
ApeAssistant13 小时前
Spring + 设计模式 (十四) 行为型 - 观察者模式
spring·设计模式