将不同的算法、封装到不同的类中、可以通过策略模式对有大量的if-else进行优化
使用策略模式计算奖金
很多公司的年终奖都是通过工资基数和年底绩效情况来发放的、比如张三今年的绩效评级是A、李四是B、A的绩效奖金是3倍工资、B是2倍工资、所以我们可以使用策略模式来计算员工的年终奖
// 策略类
class PerformanceS{
constructor(){}
calculate(salary){
return salary * 4
}
}
class PerformanceA{
constructor(){}
calculate(salary){
return salary * 3
}
}
class PerformanceB{
constructor(){}
calculate(salary){
return salary * 2
}
}
// 奖金类
class Bonus{
constructor(){
this.salary = null; // 薪资
this.strategy = null; // 绩效等级对应的策略对象
}
setSalary(salary){
this.salary = salary;
}
setStrategy(strategy){
this.strategy = strategy;
}
// 获取奖金数额
getBonus(){
return this.strategy.calculate(this.salary)
}
}
// 张三奖金
const bonus = new Bonus();
bonus.setSalary(1000)
bonus.setStrategy(new PerformanceA());
const zsMoney = bonus.getBonus() // 3000
// 李四
bonus.setSalary(2000)
bonus.setStrategy(new PerformanceB());
const lsMoney = bonus.getBonus() // 4000