js设计模式(二)---策略模式

策略模式:

定义:

  定义一系列的算法,把他们一个个封装起来,并且是他们可以相互替换

应用场景:

  要求实现某一个功能有多种方案可以选择。比如:条条大路通罗马

实现:

  场景,绩效为 S的人年终奖有 4倍工资,绩效为 A的人年终奖有 3倍工资,而绩效为 B的人年终奖是 2倍工资。假设财务部要求我们提供一段代码,来方便他们计算员工的年终奖。

var calculateBonus = function( performanceLevel, salary ){
if ( performanceLevel === 'S' ){
return salary * 4;
}
if ( performanceLevel === 'A' ){
return salary * 3;
}
if ( performanceLevel === 'B' ){
return salary * 2;
}
};
calculateBonus( 'B', 20000 ); // 输出:40000
calculateBonus( 'S', 6000 ); // 输出:24000

但是这样简单的实现会造成,calculateBonus函数过于庞大、弹性差、复用性差

我们可以改进成

//定义解决方案
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;
};
//定义奖金类 Bonus :
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() ); // 输出:40000

在js 中策略模式的使用

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', 20000)); // 输出:80000
console.log(calculateBonus('A', 10000)); // 输出:30000
原文地址:https://www.cnblogs.com/web-Rain/p/7803408.html