JS设计模式之策略模式

 1、假设现在要根据绩效计算年终奖

function rewardCalc(level, salary){
    if(level === 'S') {
        return salary * 4
    } else if(level === 'A') {
        return salary * 3
    } else if(level === 'B') {
        return salary * 2
    }
}

  //上述代码缺陷:1、if else逻辑过多函数庞大    2、缺乏弹性增加绩效就必须深入函数更改代码   3、年终奖计算方法无法复用

策略模式初步使用, 将方法抽离

const calcLevelS = salary => salary * 4
const calcLevelA = salary => salary * 3
const calcLevelB = salary => salary * 2
function rewardCalc(level, salary) {
  if(level === 'S'){
   calcLeverS(salary)  
  } else if(level === 'A'){
    calcLevelA(salary)
  } else if(level === 'B') {
    calcLevelB(salary) 
  }
}
//计算规则已经分离, 但是if else逻辑过多仍然没有解决  

再次重构,消除if语句

const calcLevelS = salary => salary * 4
const calcLevelA = salary => salary * 3
const calcLevelB = salary => salary * 2
function rewardCalc(level, salary) {
    const mapMoney = {
        S: calcLevelS,
        A: calcLevelA,
        B: calcLevelB,
    }
    return mapMoney[level](salary)
}

 

posted @ 2020-12-11 11:33  进心进利  阅读(150)  评论(0编辑  收藏  举报