一、定義
模板方法是基於繼承的設計模式,可以很好的提高系統的擴充性。 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非同步請求,把需要執行的操作封裝在回呼函數裡,當資料返回後,這個回呼函數才被執行。
希望本文所述對大家學習javascript程式設計有所協助。