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

相关推荐
GISer_Jing3 小时前
Monorepo+Pnpm+Turborepo
前端·javascript·ecmascript
天涯学馆3 小时前
前端开发也能用 WebAssembly?这些场景超实用!
前端·javascript·面试
我在北京coding4 小时前
TypeError: Cannot read properties of undefined (reading ‘queryComponents‘)
前端·javascript·vue.js
海天胜景5 小时前
vue3 获取选中的el-table行数据
javascript·vue.js·elementui
翻滚吧键盘5 小时前
vue绑定一个返回对象的计算属性
前端·javascript·vue.js
苦夏木禾5 小时前
js请求避免缓存的三种方式
开发语言·javascript·缓存
超级土豆粉5 小时前
Turndown.js: 优雅地将 HTML 转换为 Markdown
开发语言·javascript·html
乆夨(jiuze)5 小时前
记录H5内嵌到flutter App的一个问题,引发后面使用fastClick,引发后面input输入框单击无效问题。。。
前端·javascript·vue.js
小彭努力中6 小时前
141.在 Vue 3 中使用 OpenLayers Link 交互:把地图中心点 / 缩放级别 / 旋转角度实时写进 URL,并同步解析显示
前端·javascript·vue.js·交互