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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM