设计模式:策略模式
作者:互联网
设计模式:策略模式
特点
- 一个问题匹配多个解决方案
- 可以添加解决方案
- 可以删除解决方案
案例:购物车结算
- 解决方案
const sale = {
'100_10': price => price -= 10,
'200_30': price => price -= 30,
'500_60': price => price -= 60
}
- 添加解决方案
calcPrice.add = function (type, fn) {
if (sale[type]) return '此优惠已存在'
sale[type] = fn
}
- 删除解决方案
calcPrice.del = function (type) {
delete sale[type]
}
完整代码
const calcPrice = (function () {
// 优惠类型
const sale = {
'100_10': price => price -= 10,
'200_30': price => price -= 30,
'500_60': price => price -= 60
}
function calcPrice (price, type) {
if (sale[type] === undefined) return '此优惠不存在'
return sale[type](price)
}
// 添加优惠类型
calcPrice.add = function (type, fn) {
if (sale[type]) return '此优惠已存在'
sale[type] = fn
}
// 删除优惠类型
calcPrice.del = function (type) {
delete sale[type]
}
return calcPrice
})()
标签:function,return,策略,price,sale,模式,calcPrice,设计模式,type 来源: https://blog.csdn.net/m0_57835615/article/details/120589864