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

相关推荐
步行cgn22 分钟前
JSON.stringify 详解:把 JavaScript 对象变成 JSON 字符串
开发语言·javascript·json
上火的金鱼妹3 小时前
关于多进程sse连接通知的实战
javascript·状态模式·sse
console.log('npc')4 小时前
问题跟踪与知识沉淀:从任务到知识的闭环)
前端·javascript·人工智能
missile1114 小时前
# HDR 算法 ISP 通路客制化方案(G100 / mt6789)
java·前端·javascript
是2的10次方啊4 小时前
设计模式与生活⑦:你打的车,隔着一个平台
设计模式
挖掘狂人4 小时前
Vue nextTick 到底在等什么?一篇讲透原理与那些年踩过的坑
javascript·程序员·编程语言
geovindu4 小时前
rust: Read-Write Lock Pattern
开发语言·后端·设计模式·rust·读写锁模式·同步型模式
万少4 小时前
Harmony 7.0 这个skill帮你自动化操作AGC
前端·javascript·后端
小大宇4 小时前
Vue知识点-ElementPlus-02图标
前端·javascript·vue.js
谙忆10246 小时前
图像任务超时怎么重试:先分执行状态,再做结果验收
javascript