标签:
以泡茶和泡咖啡为例,可以整理为下面四步
首先创建一个抽象父类来表示泡一杯饮料
var Beverage=function(){}; Beverage.prototype.boilWater=function(){ console.log(‘把水煮沸‘); }; Beverage.prototype.brew=function(){};//空方法,由子类重写 Beverage.prototype.pourInCup=function(){};//空方法,由子类重写 Beverage.prototype.addCondiments=function(){};//空方法,由子类重写 Beverage.prototype.init=function(){ this.boilWater(); this.brew(); this.pourInCup(); this.addCondiments(); };
接下来创建Coffee子类和Tea子类
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();
继续创建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(‘加柠檬‘); }; var tea=new Tea(); tea.init();
上例中,Beverage.prototype.init是模板方法,方法中封装了子类的算法框架
它作为一个算法的模板,指导子类以何种顺序去执行哪些方法
var Beverage=function(param){ var boilWater=function(){ console.log(‘把水煮沸‘); }; var brew=param.brew||function(){ throw new Error(‘必须传递brew方法‘); }; var pourInCup=param.pourInCup||function(){ throw new Error(‘必须传递pourInCup方法‘); }; var addCondiments=param.addCondiments||function(){ throw new Error(‘必须传递addCondiments方法‘); }; var F=function(){}; F.prototype.init=function(){ boilWater(); brew(); pourInCup(); addCondiments(); }; return F; }; var Coffee=Beverage( { brew:function(){ console.log(‘用沸水冲泡咖啡‘); }, pourInCup:function(){ console.log(‘把咖啡倒进杯子‘); }, addCondiments:function(){ console.log(‘加糖和牛奶‘); } } ); var Tea=Beverage( { brew:function(){ console.log(‘用沸水浸泡茶叶‘); }, pourInCup:function(){ console.log(‘把茶倒进杯子‘); }, addCondiments:function(){ console.log(‘加柠檬‘); } } ); var coffee=new Coffee(); coffee.init(); var tea=new Tea(); tea.init();
《JavaScript设计模式与开发实践》读书笔记之模板方法模式
标签:
原文地址:http://www.cnblogs.com/GongQi/p/4657911.html