Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript设计模式(二):策略模式 #22

Open
yangrenmu opened this issue Apr 28, 2020 · 0 comments
Open

JavaScript设计模式(二):策略模式 #22

yangrenmu opened this issue Apr 28, 2020 · 0 comments
Labels

Comments

@yangrenmu
Copy link
Owner

定义

策略模式:定义一系列的算法,把他们一个个封装起来,并且使它们可以相互替换。
换句话说就是,把一些用switch语句写的判断,封装成一个一个的方法,就是策略模式。

JavaScript 中的策略模式

const strategies = {
  S: function (salary) {
    return salary * 5
  },
  A: function (salary) {
    return salary * 4
  },
  B: function (salary) {
    return salary * 3
  }
}

const calcualteBonus = function (level, salary) {
  return strategies[level](salary)
}

console.log(calcualteBonus('S', 20000)) // 100000
console.log(calcualteBonus('A', 10000)) // 40000

优点

  • 可以减少代码的耦合。
  • 复用性好。
@yangrenmu yangrenmu added the mode label Apr 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant