建设部网站刘赵云,惠州网站seo,平台与网站有什么区别,成都游戏外包公司排名设计模式#xff1a;针对特定问题提出的简洁优化的解决方案 一个问题有多种处理方案#xff0c;而且处理方案随时可能增加或减少比如#xff1a;商场满减活动 满50元减5元满100元减15元满200元减35元满500元减100元
// 满减金额计算函数
function count(money, type) {if … 设计模式针对特定问题提出的简洁优化的解决方案 一个问题有多种处理方案而且处理方案随时可能增加或减少比如商场满减活动 满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