JS设计模式-责任链模式
2022/2/5 23:42:42
本文主要是介绍JS设计模式-责任链模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
JS设计模式-责任链模式
1.
看以下代码
function distributePrizes(payMethod, isPay, prizesCount) { //充值五百 if (payMethod === 500) { if (isPay) { console.log("恭喜获得100块礼品卷"); } else { if (prizesCount) { console.log("恭喜获得10块礼品卷"); } else { console.log("抱歉,礼品券库存不足"); } } //充值两百 } else if (payMethod === 200) { if (isPay) { console.log("恭喜获得20块礼品卷"); } else { if (prizesCount) { console.log("恭喜获得10块礼品卷"); } else { console.log("抱歉,礼品券库存不足"); } } //不充值 } else { if (prizesCount) { console.log("恭喜获得10块礼品卷"); } else { console.log("抱歉,礼品券库存不足"); } } }
各种嵌套的if-else if-else让人读起来很累。不难想象的是参数通过if-elseif-else不断的判断从而向下传递,那么可以采用责任链的模式(或者说链表)来进行优化,从而满足开放封闭原则(对拓展开放修改封闭)和单一职责原则
2.
function pay500(payMethod, isPay, prizesCount) { if (isPay && payMethod === 500) { console.log("恭喜获得100块礼品卷"); } else { return "goNext"; } } function pay200(payMethod, isPay, prizesCount) { if (isPay && payMethod === 200) { console.log("恭喜获得20块礼品卷"); } else { return "goNext"; } } function nexType(payMethod, isPay, prizesCount) { if (prizesCount) { console.log("恭喜获得10块礼品卷"); } else { console.log("抱歉,礼品券库存不足"); } } function testPayChain(fn){ this.fn = fn this.nextChain = null } testPayChain.prototype.distributePrizes = function(){ var mark = this.fn.apply(this,arguments) return mark === 'goNext' && this.nextChain.distributePrizes.apply(this.nextChain,arguments) } var head = new testPayChain(function(payMethod, isPay, prizesCount){return 'goNext'}) var chain500 = new testPayChain(pay500) var chain200 = new testPayChain(pay200) var chainNexType = new testPayChain(nexType) head.nextChain = chain500 chain500.nextChain = chain200 chain200.nextChain = chainNexType head.distributePrizes(500,true,500) head.distributePrizes(200,true,500) head.distributePrizes(500,false,500) head.distributePrizes(200,false,0)
3.存在的问题
1.当链条很长的时候存在性能问题
2.当存在异步函数的时候即无法采用该方法
这篇关于JS设计模式-责任链模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-30React Native常用组件-点击组件
- 2024-05-30uniapp+vue3+uv-ui手机端后台OA管理模板
- 2024-05-29Python网络爬虫的时候json=就是让你少写个json.dumps()
- 2024-05-27React Native常用组件-展示组件
- 2024-05-27React Native常用组件-列表组件
- 2024-05-09vue3开发前端表单缓存自定义指令,移动端h5必备插件
- 2024-05-09React Hooks在class组件中的使用方式
- 2024-03-30[OIDC in Action] 2. 基于OIDC(OpenID Connect)的SSO(纯JS客户端)
- 2024-03-29terraform jsonencode
- 2024-03-13vuex-persist