JavaScript設計模式--模板方法模式
阿新 • • 發佈:2019-01-08
一、定義
模板方法是基於繼承的設計模式,可以很好的提高系統的擴充套件性。 java中的抽象父類、子類
模板方法有兩部分結構組成,第一部分是抽象父類,第二部分是具體的實現子類。
二、示例
Coffee or Tea
(1) 把水煮沸
(2) 用沸水浸泡茶葉
(3) 把茶水倒進杯子
(4) 加檸檬
/* 抽象父類:飲料 */
var Beverage = function(){};
// (1) 把水煮沸
Beverage.prototype.boilWater = function() {
console.log("把水煮沸");
};
// (2) 沸水浸泡
Beverage.prototype.brew = function () {
throw new Error("子類必須重寫brew方法");
};
// (3) 倒進杯子
Beverage.prototype.pourInCup = function() {
throw new Error("子類必須重寫pourInCup方法");
};
// (4) 加調料
Beverage.prototype.addCondiments = function() {
throw new Error("子類必須重寫addCondiments方法");
};
/* 模板方法 */
Beverage.prototype.init = function() {
this .boilWater();
this.brew();
this.pourInCup();
this.addCondiments();
}
/* 實現子類 Coffee*/
var Coffee = function(){};
Coffee.prototype = new Beverage();
// 重寫非公有方法
Coffee.prototype.brew = function() {
console.log("用沸水沖泡咖啡");
};
Coffee.prototype.pourInCup = function() {
console.log("把咖啡倒進杯子" );
};
Coffee.prototype.addCondiments = function() {
console.log("加牛奶");
};
var coffee = new Coffee();
coffee.init();
通過模板方法模式,在父類中封裝了子類的演算法框架。這些演算法框架在正常狀態下是適用大多數子類的,但也會出現“個性”子類。
如上述流程,加調料是可選的。
鉤子方法可以解決這個問題,放置鉤子是隔離變化的一種常見手段。
/* 新增鉤子方法 */
Beverage.prototype.customerWantsCondiments = function() {
return true;
};
Beverage.prototype.init = function() {
this.boilWater();
this.brew();
this.pourInCup();
if(this.customerWantsCondiments()) {
this.addCondiments();
}
}
/* 實現子類 Tea*/
var Tea = function(){};
Tea.prototype = new Beverage();
// 重寫非公有方法
Tea.prototype.brew = function() {
console.log("用沸水沖泡茶");
};
Tea.prototype.pourInCup = function() {
console.log("把茶倒進杯子");
};
Tea.prototype.addCondiments = function() {
console.log("加牛奶");
};
Tea.prototype.customerWantsCondiments = function() {
return window.confirm("需要新增調料嗎?");
};
var tea = new Tea();
tea.init();
JavaScript沒有提供真正的類式繼承,繼承是通過物件與物件之間的委託來實現的。
三、“好萊塢原則”:別調用我們,我們會呼叫你
典型使用場景:
(1)模板方法模式:使用該設計模式意味著子類放棄了對自己的控制權,而是改為父類通知子類。作為子類,只負責提供一些設計上的細節。
(2)觀察者模式:釋出者把訊息推送給訂閱者。
(3)回撥函式:ajax非同步請求,把需要執行的操作封裝在回撥函式裡,當資料返回後,這個回撥函式才被執行。