最近有時間看看書扛点,看了JavaScript設計模式與開發(fā)實踐這本書,之前草草看過這本書岂丘,已經(jīng)忘的差不多了陵究,很多關于設計模式的書都是基于類的,這本書基于javascript的語言特點講了設計模式奥帘,把看到的實踐總結一遍才會變成自己的铜邮。
單例模式
這應該是最簡單的一種設計模式,在應用中我們通常需要一個單獨的實例來實現(xiàn)一些功能翩概,比如線程池牲距,登錄框,任務隊列钥庇。
例如這樣
function Single(name) {
this.name = name;
this.instance = null;
}
Single.getInstance = function(name) {
if (!this.instance) {
this.instance = new Single(name);
}
return this.instance;
};
var a = Single.getInstance("小明");
var b = Single.getInstance("小周");
console.log(a === b);
我們實現(xiàn)一個單例的方法還需要創(chuàng)建一個類牍鞠,在執(zhí)行一個類上的方法,這樣寫代碼有些受java等面向對象語言的干擾评姨,利用js的特性可以直接實現(xiàn)一個單例模式难述,全局變量
就是唯一的一個實例,但使用全局變量會引起變量污染問題吐句,我們可以使用閉包來實現(xiàn)一個簡單的單例
// 實現(xiàn)一個代理的通用方法
var single = (function() {
var instance;
return function getInstance(fn) {
if (!instance) {
instance = fn.apply(this, [].slice.call(arguments, 1));
}
return instance;
};
})();
// 單例模式具體執(zhí)行的方法
var createDiv = function(html) {
var div = document.createElement("div");
div.innerHTML = html;
document.body.appendChild(div);
return div;
};
var div1 = single(createDiv, "single1");
var div2 = single(createDiv, "single2");
console.log(div1 === div2);
根據(jù)單一職責的實踐胁后,我們將負責單一實例的功能與具體執(zhí)行的方法分開設計,這樣保證了更好的通用性嗦枢,和方便以后對方法進行修改攀芯。其實我們在一些常用的方法中已經(jīng)用過這種模式,比如我們通常用來優(yōu)化頁面滾動的函數(shù)截流
和函數(shù)防抖
文虏。都是在滾動的時候保證只有一個單例的方法去執(zhí)行自定義的邏輯侣诺,防止函數(shù)被多次調用。
策略模式
我們在寫代碼時經(jīng)常會寫if else
邏輯判斷的代碼
例如年終評績效時得 A 會發(fā) 4 倍工資氧秘,B 是 3 倍工資年鸳,C 是 2 倍工資
/**
* 獲取年終獎金
* @param {string} performance // 績效
* @param {number} wage 基本工資
*/
function getBouns(performance, wage) {
if (performance === "A") {
return 4 * wage;
} else if (performance === "B") {
return 4 * wage;
} else if (performance === "C") {
return 4 * wage;
}
}
這是很常見的代碼編寫,當邏輯比較少的時候這樣寫是最佳的丸相,但當我們有很多判斷邏輯搔确,并且之后可能會頻繁修改就需要用到策略模式了。下邊是用傳統(tǒng)方式實現(xiàn)的策略模式
// 下邊是績效類
function performanceA() {}
performanceA.prototype.caculate = function(wage) {
return 4 * wage;
};
function performanceB() {}
performanceB.prototype.caculate = function(wage) {
return 3 * wage;
};
function performanceC() {}
performanceC.prototype.caculate = function(wage) {
return 2 * wage;
};
/**
* 工資計算類
* @param {*} performance
* @param {*} wage
*/
function Bouns(performance, wage) {
this.performance = performance;
this.wage = wage;
}
Bouns.prototype.getBouns = function() {
return this.performance.caculate(this.wage);
};
var bouns = new Bouns(new performanceA(), 10000);
console.log(bouns.getBouns());
在 java中我們要實現(xiàn)任何方法都要依賴類來實現(xiàn),通過類去實例化對象膳算。我們想要針對不同的條件去執(zhí)行不同的類座硕,其實還是要ifelse
的判斷。二期對于一個固定的對象我們還實現(xiàn)了構造函數(shù)畦幢,有些畫蛇添足坎吻。在js中我們可以直接定義對象字面量缆蝉,向下邊這樣
// 定義所有策略對象
var performances = {
A: function(wage) {
return wage * 4;
},
B: function(wage) {
return wage * 3;
},
C: function(wage) {
return wage * 2;
}
};
function getBouns(performance, wage) {
if (performances[performance]) {
return performances[performance](wage);
}
throw new Error("performance is not define");
}
var bouns = getBouns("A", 10000);
console.log(bouns);
這里直接使用一個對象來接收所有計算獎金的邏輯宇葱,我們的業(yè)務代碼getBouns
在遇到修改比如我想加一個S的績效不用改變,我們直接修改performances
這個承載所有計算邏輯的對象就可以實現(xiàn)業(yè)務的修改
這里再舉一個例子刊头,我們可以使用策略模式實現(xiàn)一個js動畫黍瞧,我們使用動畫的時候經(jīng)常會用css的動畫,transtion
的屬性有ease,linear
代表運動速率函數(shù)原杂,left,width
代表要改變的css屬性印颤,我們可以使用策略模式來簡單實現(xiàn)一個基于js的動畫方法
// 計算運動的算法,4個參數(shù)是已消耗時間穿肄,原始位置年局,位置間的差距,持續(xù)的總時間
const motions = {
linear: function(t, b, c, d) {
return (c * t) / d + b;
},
ease: function(t, b, c, d) {
return c * (t /= d) * t + b;
}
};
/**
* 動畫的主方法咸产,模仿css的屬性參數(shù)
*/
class Animate {
/**
*
* @param {*} dom 需要修改的dom元素
* @param {*} property 要改變的style屬性
* @param {*} target 改變style的目標值
* @param {*} time 運動的時間
* @param {*} motion 運動函數(shù)
*/
constructor(dom, property, target, time, motion) {
this.dom = document.querySelector(dom);
this.property = property;
this.startDom = +getComputedStyle(this.dom)[property].replace("px", "");
this.startTime = +new Date();
this.curTime = this.startTime;
this.time = time;
this.end = this.startTime + time;
this.endDom = target;
this.motion = motions[motion];
}
/**
* 開始執(zhí)行動畫
*/
start() {
this.timer = setInterval(() => {
this.step();
}, 60);
}
// 每一步執(zhí)行的具體步驟
step() {
this.curTime = +new Date();
if (this.curTime > this.end) {
clearInterval(this.timer);
this.update(this.endDom);
return;
}
var p = this.motion(
this.curTime - this.startTime,
this.startDom,
this.endDom - this.startDom,
this.time
);
this.update(p);
}
// 更新dom的方法
update(value) {
this.dom.style[this.property] = value + "px";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#box{
background: red;
width: 100px;
height: 200px;
}
</style>
</head>
<body>
<div id="box"></div>
<script src="./Animate.js"></script>
<script>
window.onload = function(){
var animate = new Animate("#box", "width", 200, 1000, "linear")
animate.start()
}
</script>
</body>
</html>
這樣利用策略模式我們就可以模擬一個類似css動畫的方法庫矢否,在頁面中可以看到一個方塊勻速變大到200px的過程。我們想換一種運動方式只需要將linear
改為ease
脑溢。還有很多種實際應用僵朗,我們可以在實際開發(fā)中應用,例如表單校驗屑彻,目前組件化流行验庙,根據(jù)不同的數(shù)據(jù)展示不同的組件。都可以幫我們更好的優(yōu)化代碼社牲。不用設計也可以實現(xiàn)所有功能粪薛,設計模式只是幫我們更好的使代碼邏輯更清晰,更好維護代碼搏恤,更好復用代碼违寿。