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 分钟前
[前端高频]数组转树、数组扁平化、深拷贝、JSON.stringify&JSON.parse等手撕
前端·javascript·json
古拉拉明亮之神18 分钟前
Spark处理过程-转换算子
javascript·ajax·spark
岁岁岁平安1 小时前
Vue3学习(组合式API——Watch侦听器、watchEffect()详解)
前端·javascript·vue.js·学习·watch侦听器·组合式api
Stringzhua2 小时前
JavaScript入门【3】面向对象
javascript
2501_915373882 小时前
Vue路由深度解析:Vue Router与导航守卫
前端·javascript·vue.js
Brilliant Nemo4 小时前
Vue2项目中使用videojs播放mp4视频
开发语言·前端·javascript
软考真题app4 小时前
软件设计师考试结构型设计模式考点全解析
设计模式·软件设计师·结构型设计模式·考试考点
酷爱码4 小时前
Linux实现临时RAM登录的方法汇总
linux·前端·javascript
Wannaer5 小时前
从 Vue3 回望 Vue2:性能优化内建化——从黑盒优化到可控编译
javascript·vue.js·性能优化
yyywoaini~5 小时前
wordcount程序
前端·javascript·ajax