将不同的算法、封装到不同的类中、可以通过策略模式对有大量的if-else进行优化

使用策略模式计算奖金

很多公司的年终奖都是通过工资基数和年底绩效情况来发放的、比如张三今年的绩效评级是A、李四是B、A的绩效奖金是3倍工资、B是2倍工资、所以我们可以使用策略模式来计算员工的年终奖

  1. // 策略类
  2. class PerformanceS{
  3. constructor(){}
  4. calculate(salary){
  5. return salary * 4
  6. }
  7. }
  8. class PerformanceA{
  9. constructor(){}
  10. calculate(salary){
  11. return salary * 3
  12. }
  13. }
  14. class PerformanceB{
  15. constructor(){}
  16. calculate(salary){
  17. return salary * 2
  18. }
  19. }
  20. // 奖金类
  21. class Bonus{
  22. constructor(){
  23. this.salary = null; // 薪资
  24. this.strategy = null; // 绩效等级对应的策略对象
  25. }
  26. setSalary(salary){
  27. this.salary = salary;
  28. }
  29. setStrategy(strategy){
  30. this.strategy = strategy;
  31. }
  32. // 获取奖金数额
  33. getBonus(){
  34. return this.strategy.calculate(this.salary)
  35. }
  36. }
  37. // 张三奖金
  38. const bonus = new Bonus();
  39. bonus.setSalary(1000)
  40. bonus.setStrategy(new PerformanceA());
  41. const zsMoney = bonus.getBonus() // 3000
  42. // 李四
  43. bonus.setSalary(2000)
  44. bonus.setStrategy(new PerformanceB());
  45. const lsMoney = bonus.getBonus() // 4000

总结

优点

  • 符合开闭原则
  • 避免代码冗余,避免出现大量的if-else,switch语句、扩展也好,有其他条件只需要新增策略对象就好

    缺点

  • 客户端必须要知道所有的策略类,并且自行决定使用那个策略类

  • 增加复杂性,如果系统很复杂,会产生很多策略类