当前位置: 首页 > news >正文

JS-策略设计模式

设计模式:针对特定问题提出的简洁优化的解决方案

  • 一个问题有多种处理方案,而且处理方案随时可能增加或减少
  • 比如:商场满减活动
    • 满50元减5元
    • 满100元减15元
    • 满200元减35元
    • 满500元减100元
// 满减金额计算函数
function count(money, type) {if (type == '50_5') {return money - 5;} else if (type == '100_15') {return money - 15;} else if (type == '200_35') {return money - 35;} else if (type == '500_100') {return money - 100;} else {return money;}
}console.log(count(60, '50_5')); // 55
console.log(count(101, '100_15')); // 86
  • 商场活动中,若需要增加或减少满减方案,则需要修改count函数
    • 代码封装应该遵循“开闭原则”,此时就应该使用策略设计模式
      • 可以将满减方案存储在对象中,使用闭包函数存储数据(满减方案)
      • 并且在闭包函数中,实现添加或移除折扣方案的方法
let count = (function() {// 满减折扣方案let countObj = {'50_5': function(money) { return money - 5 },'100_15': function(money) { return money - 15 },'200_35': function(money) { return money - 35 },'500_100': function(money) { return money - 100 }}// 金额计算function count(money, type) {if (countObj[type]) { // 折扣存在则使用折扣满减return countObj[type](money);}return money;}// 给count函数对象添加add方法(新增方案)count.add = function(type, fn) {countObj[type] = fn;}// 给count函数对象添加remove方法(移除方案)count.remove = function(type) {delete countObj[type];}return count;
})();// 使用折扣计算金额
console.log(count(60, '50_5')); // 55
console.log(count(100, '100_15')); // 85
console.log(count(600, '500_100')); // 500// 添加折扣方案
count.add('600_120', function(money) { return money - 120 });
console.log(count(600, '600_120')); // 480// 移除折扣方案
count.remove('50_5');
console.log(count(60, '50_5')); // 60
http://www.lryc.cn/news/289478.html

相关文章:

  • 漏洞复现-EduSoho任意文件读取漏洞(附漏洞检测脚本)
  • 「QT」QString类的详细说明
  • 微信小程序-04
  • 什么是数据库的三级模式两级映象?
  • 初识人工智能,一文读懂机器学习之逻辑回归知识文集(6)
  • 2024 CKA 题库 | 15、备份还原 etcd
  • 基于Matlab/Simulink直驱式风电储能制氢仿真模型
  • 计算机网络(第六版)复习提纲16
  • 【AndroidStudio】2022.3Giraffe连接超时,更换下载源,使用本地gradle,版本对应问题
  • 【Midjourney】内容展示风格关键词
  • openssl3.2/test/certs - 056 - all DNS-like CNs allowed by CA1, no SANs
  • mysql INSERT数据覆盖现有元素(若存在)
  • 攻防世界WEB新手训练区
  • Go语言安装及开发环境配置
  • 知识搜索术学习笔记
  • 【深度学习】sdxl中的 tokenizer tokenizer_2 区别
  • 使用一个定时器(timer_fd)管理多个定时事件
  • C++:使用tinyXML生成矢量图svg
  • day34_js
  • AR 自回归模型
  • 51单片机ESP8266
  • php 源码加密保护 bease方案
  • FFMPEG解析ts流
  • Java基础-实现猜数字小游戏
  • 爬虫(一)
  • 【软件测试】学习笔记-Nginx 在系统架构中的作用
  • 鸿蒙开发【应用开发基础知识】
  • 腾讯云幻兽帕鲁4核16G14M服务器性能测评和价格
  • Linux第一个小程序——进度条
  • (N-141)基于springboot,vue网上拍卖平台