【D1n910】第 19 章 活諸葛 —— 策略模式
正常操作,正常分析,大家好,我是D1n910。
今天我繼續(xù)來學(xué)習(xí) 《JavaScript 設(shè)計模式》的第四篇 行為型設(shè)計模式
這是一個連續(xù)的讀書筆記,所以如果你之前的內(nèi)容沒有看的話,可以去看看(建議直接看書,當(dāng)然書的例子都比較早了,是2015年之前的代碼內(nèi)容,過了六年了,前端發(fā)展了很多,比如類的聲明可以直接用 Class 了)。
直接查看目錄就可以查看到所有的系列文章啦。

這里再次感謝 《Javascript 設(shè)計模式》及其作者 張榮銘,專欄內(nèi)容是在它的基礎(chǔ)上生成的。
現(xiàn)在會覺得很多設(shè)計模式離我們有點遙遠(yuǎn),是因為我們現(xiàn)在都在用大佬寫好的框架吧,很多設(shè)計模式都包含在框架里了。
后面有機會的話,我希望我可以查看目前主流框架的源代碼,然后進行講解。

第四篇 行為型設(shè)計模式
行為型設(shè)計模式用于不同對象之間職責(zé)劃分或算法抽象,行為型設(shè)計模式不僅僅涉及類和對象,還涉及類或?qū)ο笾g的交流模式并加以實現(xiàn)。
第 19 章 活諸葛 —— 策略模式
策略模式(Strategy):將定義的一組算法封裝起來,使其相互之間可以替換。封裝的算法具有一定的獨立性,不會隨著客戶變化而變化。
公司的網(wǎng)站做促銷活動,希望頁面上商品價格能夠按照不同的促銷方式進行展示。
促銷方式有四種
1、滿 100 - 40
2、滿 100 - 30
3、打九折
4、打八折
考慮可以把這些價格策略算法抽離出來放到一個對象中,這樣不同的工程都能使用。

最終

var productList = [
{
name: '商品1',
price: 100.11,
discount: 'return40'
},
{
name: '商品2',
price: 45.11,
discount: 'return30'
},
{
name: '商品3',
price: 90.11,
discount: 'percent9'
},
{
name: '商品4',
price: 40.11,
discount: 'percent8'
}
]
var priceStrategy = function () {
? ?// 內(nèi)部算法對象
? ?var strategy = {
? ? ? ?return40: function (price) {
? ? ? ? ? ?return +price - ?parseInt(price / 100) * 40;
? ? ? ?},
? ? ? ?return30: function (price) {
? ? ? ? ? ?return +price - ?parseInt(price / 100) * 30;
? ? ? ?},
? ? ? ?percent9: function (price) {
? ? ? ? ? ?return price * 100 * 90 / 10000;
? ? ? ?},
? ? ? ?percent8: function (price) {
? ? ? ? ? ?return price * 100 * 80 / 10000;
? ? ? ?}
? ?}
? ?return function (type, price) {
? ? ? ?return strategy[type] && strategy[type](price)
? ?}
}();
class ProductContainer {
constructor(productList) {
? ? ? ?var container = document.createElement('ul');
? ? ? ?for (let i of productList) {
? ? ? ? ? ?var productLi = document.createElement('li');
? ? ? ? ? ?productLi.innerHTML = '產(chǎn)品名稱:' + i.name + ' ' + '原價格: ' + i.price + ' 現(xiàn)在價格: ' + priceStrategy(i.discount, i.price);
? ? ? ? ? ?container.appendChild(productLi);
? ? ? ?}
? ? ? ?document.body.appendChild(container);
? ?}
}
new ProductContainer(productList);
策略模式
優(yōu)點:
1、封裝了一組代碼蔟,并且封裝的代碼之間相互獨立,便于對算法的重復(fù)利用,提高了算法的復(fù)用率;
2、與繼承相比,類上的算法不易改變,不易演化;
3、優(yōu)化分支判斷語句,使得算法更利于維護。
缺點:
1、想要選擇哪種算法的決定權(quán)在用戶,所以用戶需要了解每個算法的實現(xiàn),增加了使用成本;
2、算法之間相互獨立,所以復(fù)發(fā)的算法處理相同邏輯的部分無法實現(xiàn)共享,就會造成資源的浪費。
本章 End
D1n910 于2021年02月26日在南山后海