策略模式

110 阅读1分钟

为了解决过多的 if...else 的嵌套问题

策略模式的核心(当前案例)

创建一个数据结构, 这个解构内存储着各种折扣记录, 对应的值 是这个折扣的计算方式

               '8折': 商品总价 * 80%,
               '7折': 商品总价 * 70%,
               '5折': 商品总价 * 50%,
               '9折': 商品总价 * 90%,

    
        // 基础版
         if ('8折') {
             console.log('商品总价的 * 80%')
         } else if ('85折') {
             console.log('商品总价的 * 85%')
         } else if ('95折') {
             console.log('商品总价的 * 95%')
         } else if ('9折') {
             console.log('商品总价的 * 90%')
         }

        // 策略模式优化
        const calcPrice = (function () {
            // 当前对象内存储着各种折扣, 以及对应的 打折后商品总价的计算方式
            const calcList = {
                '80%': (total) => { return (total * 0.8).toFixed(1) },
                '70%': (total) => { return (total * 0.7).toFixed(1) },
            }

            function inner(type, total) {
                /**
                 *  type: 表明当前几折
                 *  total: 打折前的商品总价
                 * 
                 *  调用当前函数是想得到 打折后的商品总价, 所以我们需要书写一个 return
                */
                return calcList[type](total)
            }

            return inner
        })()

        console.log(calcPrice('80%', 500))
        console.log(calcPrice('80%', 1000))
        console.log(calcPrice('80%', 876.3))
        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 () {
                return calcList
            }

            return inner
        })()

        console.log(calcPrice('80%', 500))
        console.log(calcPrice('80%', 1000))
        console.log(calcPrice('80%', 876.3))

        // calcPrice.add('50%', total => (total * 0.5).toFixed(1))
        // calcPrice.add('88%', total => (total * 0.88).toFixed(1))

        // calcPrice.sub('60%')

        console.log(calcPrice.getList())