• 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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    1. 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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
  • 相关阅读:
    Spring IOC理论
    shell编程增强
    2022/11/18[指针] 关于指针的初步理解
    汽车电子专有名词与相应技术
    GPU并行计算- 基础知识
    如何优雅的杀掉一个进程
    产业“上链”至深处,京东云如何作为?
    springcloud整合seata
    基于STM32设计的云端健康管理系统(采用阿里云物联网平台)
    音频驱动嘴型的视频数字人虚拟主播工具motionface replay使用教程
  • 原文地址:https://blog.csdn.net/m0_38102188/article/details/134206098