十年網站開發(fā)經驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網站問題一站解決
這篇文章主要講解了如何使用javascript中的策略模式,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
介紹:策略模式中可以定義一些獨立的類來封裝不同的算法,每一個類封裝一種具體的算法。在這里,每一種算法的封裝都可以稱之為一種策略。策略模式的主要目的是將算法的定義與使用分開。
定義:定義一系列算法類,將每一個算法封裝起來,并讓它們可以相互替換。策略模式讓算法獨立與使用它的客戶而變化,也稱為政策模式。策略模式是一種對象行為型模式。
場景:使用策略模式實現一個加減乘除的工具類,將四個算法進行封裝。
示例:
var AddStrategy = function(){ this.caculate = function(num1, num2){ return num1 + num2; } } var SubStrategy = function(){ this.caculate = function(num1, num2){ return num1 - num2; } } var MulStrategy = function(){ this.caculate = function(num1, num2){ return num1 * num2; } } var DivStrategy = function(){ this.caculate = function(num1, num2){ return num1 / num2; } } var Context = function(strategy){ var _strategy = strategy; this.executeStrategy = function(num1, num2){ return _strategy.caculate(num1, num2) } } var add = new Context(new AddStrategy()); var sub = new Context(new SubStrategy()); var mul = new Context(new MulStrategy()); var div = new Context(new DivStrategy()); console.log('1 + 2 = ' + add.executeStrategy(1, 2)); console.log('5 - 1 = ' + sub.executeStrategy(5, 1)); console.log('3 * 2 = ' + mul.executeStrategy(3, 2)); console.log('8 / 2 = ' + div.executeStrategy(8, 2)); // 1 + 2 = 3 // 5 - 1 = 4 // 3 * 2 = 6 // 8 / 2 = 4