JavaScript设计模式之责任链模式

适用场景:一个完整的流程,中间分成多个环节,各个环节之间存在一定的顺序关系,同时中间的环节的个数不一定,可能添加环节,也可能减少环节,只要保证顺序关系就可以。

如下图:

  1. ES5写法

    const Chain = function (fn) {
    this.fn = fn
    this.nextChain = null
    this.setNext = function (nextChain) {
    this.nextChain = nextChain
    return this.nextChain
    }
    this.run = function () {
    this.fn()
    this.nextChain && this.nextChain.run()
    }
    }
    //申请设备
    const applyDevice = function () {
    console.log(111)
    }
    const chainApplyDevice = new Chain(applyDevice);
    //选择收货地址
    const selectAddress = function () {
    console.log(222)
    }
    const chainSelectAddress = new Chain(selectAddress);
    //选择审核人
    const selectChecker = function () {
    console.log(333)
    }
    const chainSelectChecker = new Chain(selectChecker);

    chainApplyDevice.setNext(chainSelectAddress).setNext(chainSelectChecker);
    chainApplyDevice.run(); //最后执行结果为111-222-333

  2. ES6写法

    class Chain {
    constructor(fn) {
    this.fn = fn
    this.nextChain = null
    }
    setNext (nextChain) {
    this.nextChain = nextChain
    return this.nextChain
    }
    run() {
    this.fn()
    this.nextChain && this.nextChain.run()
    }
    }
    //申请设备
    const applyDevice = function () {
    console.log(111)
    }
    const chainApplyDevice = new Chain(applyDevice);
    //选择收货地址
    const selectAddress = function () {
    console.log(222)
    }
    const chainSelectAddress = new Chain(selectAddress);
    //选择审核人
    const selectChecker = function () {
    console.log(333)
    }
    const chainSelectChecker = new Chain(selectChecker);

    chainApplyDevice.setNext(chainSelectAddress).setNext(chainSelectChecker);
    chainApplyDevice.run(); //最后执行结果为111-222-333

相关推荐
芝士熊爱编程1 小时前
创建型模式-单例模式
java·单例模式·设计模式
森林的尽头是阳光1 小时前
tree回显问题
javascript·vue.js·elementui
weixin_BYSJ19872 小时前
「课设设计」springboot校园超市助购系统26449 (附源码)
java·javascript·spring boot·python·django·flask·php
mfxcyh3 小时前
Vue3+Ant Design Vue 实现手动异步文件上传(含大小校验、弹窗上传)
前端·javascript·vue.js
meilindehuzi_a3 小时前
Vue3进阶基础:指令修饰符、v-model表单绑定、动态样式、计算属性与侦听器实战
前端·javascript·vue.js
csdn2015_3 小时前
vue 前端运行命令
前端·javascript·vue.js
Cobyte3 小时前
根据浏览器解析 HTML 的规范实现 HTML 解析器
前端·javascript·vue.js
咖啡八杯4 小时前
GoF设计模式——访问者模式
设计模式·访问者模式
默_笙4 小时前
😁 LLM 不知道的事它不会说"不知道",而是会"编"——RAG 就是让它闭嘴先查资料
前端·javascript
Revolution614 小时前
变量提升到底提升了什么:为什么 var 是 undefined,let 却直接报错
前端·javascript