本文實(shí)例講述了JavaScript設(shè)計(jì)模式之模板方法模式原理與用法。分享給大家供大家參考,具體如下:
一、模板方法模式:一種只需使用繼承就可以實(shí)現(xiàn)的非常簡(jiǎn)單的模式。
二、模板方法模式由兩部分組成,第一部分是抽象父類,第二部分是具體的實(shí)現(xiàn)子類。
三、以設(shè)計(jì)模式中的Coffee or Tea來(lái)說(shuō)明模板方法模式:
1、模板Brverage,代碼如下:
var Beverage = function(){}; Beverage.prototype.boilWater = function(){ console.log('把水煮沸'); }; Beverage.prototype.pourInCup = function(){ throw new Error( '子類必須重寫(xiě)pourInCup' ); }; Beverage.prototype.addCondiments = function(){ throw new Error( '子類必須重寫(xiě)addCondiments方法' ); }; Beverage.prototype.customerWantsConditions = function(){ return true; //默認(rèn)需要調(diào)料 }; Beverage.prototype.init = function(){ this.boilWater(); this.brew(); this.pourInCup(); if(this.customerWantsCondiments()){ //如果掛鉤返回true,則需要調(diào)料 this.addCondiments(); } };