设计模式:策略模式
特点
- 一个问题匹配多个解决方案
- 可以添加解决方案
- 可以删除解决方案
案例:购物车结算
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
})()