当前位置:首页 > 编程笔记 > 正文
已解决

JavaScript设计模式之责任链模式

来自网友在路上 176876提问 提问时间:2023-11-04 09:14:36阅读次数: 76

最佳答案 问答题库768位专家为你答疑解惑

适用场景:一个完整的流程,中间分成多个环节,各个环节之间存在一定的顺序关系,同时中间的环节的个数不一定,可能添加环节,也可能减少环节,只要保证顺序关系就可以。
如下图:
在这里插入图片描述

  1. ES5写法
const Chain = function (fn) {this.fn = fnthis.nextChain = nullthis.setNext = function (nextChain) {this.nextChain = nextChainreturn 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. ES6写法
class Chain {constructor(fn) {this.fn = fnthis.nextChain = null}setNext (nextChain) {this.nextChain = nextChainreturn 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
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"JavaScript设计模式之责任链模式":http://eshow365.cn/6-31679-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!