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

相关推荐
用户6802659051196 小时前
如何利用 Endpoint Central 提高企业终端管理效率
javascript·后端·面试
咖啡の猫7 小时前
TypeScript 开发环境搭建
前端·javascript·typescript
是你的小橘呀7 小时前
单页应用路由怎么搞?React Router 从原理到实战全解析!
前端·javascript
风止何安啊7 小时前
Set/Map+Weak三剑客的骚操作:JS 界的 “去重王者” ,“万能钥匙”和“隐形清洁工”
前端·javascript·面试
2501_944446007 小时前
Flutter&OpenHarmony文本输入组件开发
前端·javascript·flutter
WebRuntime8 小时前
所有64位WinForm应用都是Chromium浏览器(2)
javascript·c#·.net·web
贺今宵8 小时前
2025.electron-vue3-sqlite3使用
前端·javascript·electron
Irene19918 小时前
创建新DOM节点方式总结
javascript·dom
Geoking.8 小时前
【设计模式】理解单例模式:从原理到最佳实践
单例模式·设计模式
2501_946233898 小时前
Flutter与OpenHarmony大师详情页面实现
android·javascript·flutter