JS 策略模式

130 阅读1分钟

策略模式

js
    只是为了解决代码中  过多的 if...else  嵌套的问题
    策略模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,
    且算法的变化不会影响使用算法的客户。

    策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,
    并委派给不同的对象对这些算法进行管理。

    简而言之,就是策略模式准备了一组算法,并将每个算法进行封装,使它们之间可用相互替换。

    策略模式除了用来封装算法,也可以用来封装一系列的"业务规则",
    只要这些业务规则指向的目标一致,并且可以被替换使用,我们就可以用策略模式来封装它们
    

代码展示(案例)

js
    <script>
        const calcPrice = (() => {
            const priceList = {
                '80%': total => total * 0.8,
                '70%': total => total * 0.7,
                '60%': total => total * 0.6,
            }

            function inner(total,type) {
                return priceList[type](total)
            }

            inner.add = (key,value) => {
                priceList[key] = value
            }

            inner.del = (key) => {
                delete priceList[key]
            }

            inner.get = () => {
                return priceList
            }
            return inner
        })()


        let res = calcPrice(1000,'80%')
        console.log(res)  // 800
        calcPrice.add('100-10',(total) => {
            total - Math.floor(total / 100) * 10
        })

        console.log(calcPrice.get())  // {80%: ƒ, 70%: ƒ, 60%: ƒ, 100-10: ƒ}

    </script>