策略模式
- 为了解决过多的 if...else的嵌套问题
- 策略模式的核心(当前案例)
- 创建一个数据结构,这个结构的内存储着各种折扣记录,对应的值是这个折扣的计算方式
{ '8折': 商品总价 * 80%, '7折': 商品总价 * 70%, '5折': 商品总价 * 50%, '9折': 商品总价 * 90%, }
const calcPrice = (function() {
const calcList = {
'80%': (total) => {return (total * 0.8).toFixed(1)},
'70%': (total) => {return (total * 0.8).toFixed(1)},
}
function inner(type, total) {
return calcList[type](total)
}
return inner
})()
console.log(calcPrice('80%', 500))
策略模式2
const calcPrice = (function() {
const calcList = {
'80%': (total) => {return (total * 0.8).toFixed(1)},
'70%': (total) => {return (total * 0.7).toFixed(1)},
'60%': (total) => (total * 0.6).toFixed(1),
}
function inner(type, total) {
return calcList[type](total)
}
inner.add = function(type, fn) {
calcList[type] = fn
}
inner.sub = function(type) {
delete calcList[type]
}
inner.getList = function(type) {
return calcList
}
return inner
})()
console.log(calcPrice('80%', 500))
calcPrice.add('50%', (total) => (total * 0.5).toFixed(1))
calcPrice.sub('60%')
console.log(calcPrice.getList())