學習JavaScript設計模式之模板方法模式_javascript技巧

來源:互聯網
上載者:User

一、定義

模板方法是基於繼承的設計模式,可以很好的提高系統的擴充性。 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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.