策略模式

88 阅读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%')
    // }
    // 策略模式优化
    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) {
        /**
         * type: 表明当前几折
         * total: 打折前的商品总价
         * 
         * 调用当前函数是想得到 打折后的商品总价,所以我们需要写一个 return
         * */ 
        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]
        // console.log(calcList)
      }
      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())