《JavaScript设计模式与开发实践》读书笔记之模板方法模式
2015-07-18 23:44
615 查看
1. 模板方法模式
1.1 面向对象方式实现模板方法模式
以泡茶和泡咖啡为例,可以整理为下面四步把水煮沸
用沸水冲泡饮料
把饮料倒进杯子
加调料
首先创建一个抽象父类来表示泡一杯饮料
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是模板方法,方法中封装了子类的算法框架
它作为一个算法的模板,指导子类以何种顺序去执行哪些方法
1.2 Javascript中的模板方法模式
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();
相关文章推荐
- [BZOJ1012][JSOI2008]最大数maxnumber
- json 总结
- js笔记
- 网页性能之HTML,CSS,JavaScript
- JavaScript学习要点(二)
- JavaScript匿名函数与闭包
- [LeetCode][JavaScript]Sliding Window Maximum
- Javascript下IE与Firefox下的差异兼容写法总结
- VS 2013 配置jsoncpp 库(亲测可行)
- JavaScript中逗号运算符和this
- JavaScript---DOM文档
- JS中怎么将json对象转化成字符串
- 【JavaScript】——JS入门
- JDK8在Java转让Javascript脚本引擎动态地定义和运行代码
- a href="" 和 href="#" 以及 href="javascript:void(0)"时 以及其中的 onclick 的区别
- javascript深入理解js闭包
- extjs url中文乱码处理 -- encodeURI(filePath)
- js中对radio和checkbox是否选中的判断
- javascript中获取string的长度
- javaScript 删除确认实现方法总结分享