JavaScript设计模式之模板方法模式原理与用法示例-创新互联
本文实例讲述了JavaScript设计模式之模板方法模式原理与用法。分享给大家供大家参考,具体如下:

一、模板方法模式:一种只需使用继承就可以实现的非常简单的模式。
二、模板方法模式由两部分组成,第一部分是抽象父类,第二部分是具体的实现子类。
三、以设计模式中的Coffee or Tea来说明模板方法模式:
1、模板Brverage,代码如下:
var Beverage = function(){};
Beverage.prototype.boilWater = function(){
console.log('把水煮沸');
};
Beverage.prototype.pourInCup = function(){
throw new Error( '子类必须重写pourInCup' );
};
Beverage.prototype.addCondiments = function(){
throw new Error( '子类必须重写addCondiments方法' );
};
Beverage.prototype.customerWantsConditions = function(){
return true; //默认需要调料
};
Beverage.prototype.init = function(){
this.boilWater();
this.brew();
this.pourInCup();
if(this.customerWantsCondiments()){
//如果挂钩返回true,则需要调料
this.addCondiments();
}
};
文章题目:JavaScript设计模式之模板方法模式原理与用法示例-创新互联
文章地址:http://www.jxjierui.cn/article/dppiii.html


咨询
建站咨询
