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

相关推荐
ew452182 小时前
ElementUI表格表头自定义添加checkbox,点击选中样式不生效
前端·javascript·elementui
画月的亮2 小时前
element-ui 使用过程中遇到的一些问题及解决方法
javascript·vue.js·ui
m0_526119402 小时前
点击el-dialog弹框跳到其他页面浏览器的滚动条消失了多了 el-popup-parent--hidden
javascript·vue.js·elementui
工业甲酰苯胺5 小时前
Vue3 基础概念与环境搭建
前端·javascript·vue.js
lyj1689975 小时前
el-tree选中数据重组成树
javascript·vue.js·elementui
鎈卟誃筅甡7 小时前
JavaScript设计模式 -- 迭代器模式
设计模式·迭代器模式
xiangxiongfly9157 小时前
Java 设计模式之迭代器模式
java·设计模式·迭代器模式
FLZJ_KL7 小时前
【设计模式】【行为型模式】迭代器模式(Iterator)
java·设计模式·迭代器模式
卷福同学7 小时前
设计模式2:单例模式
java·单例模式·设计模式
lonelyhiker7 小时前
javascript的原型链
开发语言·javascript·原型模式