策略模式

2021-01-14  本文已影响0人  Sommouns

优化前代码:

var calculateSalary = function (performanceLevel, salary) {
  if (performanceLevel === 'S') {
    return salary * 3
  }
  else if (performanceLevel === 'A') {
    return salary * 2
  }
  else if (performanceLevel === 'B') {
    return salary 
  }
}

当要多加一次绩效的时候需要改源码,违反开闭原则,重构后

var strategy = {
 'S': function (count) {
    return count * 3
  },
 'A': function (count) {
    return count * 2
  },
  'B': function (count) {
    return count 
  },
}

var calculateSalary = function (performanceLevel, salary) {
  return strategy[performanceLevel && strategy[performanceLevel](salary)
}

核心

上一篇下一篇

猜你喜欢

热点阅读