JavaScript设计模式之责任链模式

编程入门 行业动态 更新时间:2024-10-09 05:20:30

JavaScript设计<a href=https://www.elefans.com/category/jswz/34/1771241.html style=模式之责任链模式"/>

JavaScript设计模式之责任链模式

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

  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

更多推荐

JavaScript设计模式之责任链模式

本文发布于:2023-11-17 10:48:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640993.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   责任   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!