策略模式:定义一系列的算法,把他们一个个封装起来,并且使他们可以相互替换。
基础实现
var performanceS = function(){};
performanceS.prototype.calculate = function(salary){
return salary*4;
}
var performanceA = function(){};
performanceA.prototype.calculate = function(salary){
return salary*3;
}
var performanceB = function(){};
performanceB.prototype.calculate = function(salary){
return salary*2;
}
//定义奖金类
var Bonus = function(){
this.salary = null;
this.strategy = null;
}
Bonus.prototype.setSalary = function(salary){
this.salary = salary;
}
Bonus.prototype.setStrategy = function(strategy){
this.strategy = strategy;
}
Bonus.prototype.getBonus = function(){
return this.strategy.calculate(this.salary)
}
var bonus = new Bonus();
bonus.setSalary(10000);
bonus.setStrategy(new performanceS())
console.log(bonus.getBonus())
使用策略模式修改
var strategies = {
"S":function(salary){
return salary*4;
},
"A":function(salary){
return salary*3;
},
"B":function(salary){
return salary*2;
}
}
var calculateBonus = function(level,salary){
return strategies[level](salary);
}
console.log(calculateBonus('S',2000))