设计模式-模板方法模式
来源:互联网 发布:mac哪个适合唇色深的 编辑:程序博客网 时间:2024/06/01 07:11
1.描述:模板方法模式是一种只需要使用继承就可以实现的非常简单的模式,模式由两部分组成-抽象父类和具现子类。通常在抽象父类中封装了子类的算法框架。
2.实例:Coffee or Tea
父类-饮料-步骤:
- 把水煮沸
- 用沸水冲泡饮料
- 把饮料倒进杯子
- 加调料
var Beverage = function(){};Beverage.prototype.boilWater = function(){ console.log('把水煮沸');}Beverage.prototype.brew = function(){ throw new Error('子类必须重写brew方法');}Beverage.prototype.pourInCup = function(){ throw new Error('子类必须重写pourInCup方法');}Beverage.prototype.addCondiments = function(){ throw new Error('子类必须重写addCondiments方法');}Beverage.prototype.ifWantsCondiments = function(){//钩子方法 return true;//是否加调料}Beverage.prototype.init = function(){ this.boilWater(); this.brew(); this.pourInCup(); if(this.ifWantsCondiments()){ this.addCondiments(); }}//子类coffeevar CoffeeWithHook = function(){};CoffeeWithHook.prototype = new Beverage();CoffeeWithHook.prototype.brew = function(){ console.log('用沸水冲泡咖啡');};CoffeeWithHook.prototype.pourInCup = function(){ console.log('把咖啡倒进杯子');};CoffeeWithHook.prototype.addCondiments= function(){ console.log('加糖和牛奶');};CoffeeWithHook.prototype.ifWantsCondiments= function(){ return window.confirm('请问需要加调料吗?');};//泡一杯咖啡var coffee = new CoffeeWithHook();coffee.init();
阅读全文
0 0
- 设计模式:模板方法模式
- 设计模式 - 模板方法模式
- 设计模式:模板方法模式
- 设计模式 模板方法模式
- 设计模式--模板方法模式
- 设计模式-【模板方法模式】
- 设计模式: 模板方法模式
- 设计模式- 模板方法模式
- 设计模式 - 模板方法模式
- 设计模式 - 模板方法模式
- 设计模式-模板方法模式
- 设计模式-模板方法模式
- 设计模式---模板方法模式
- 设计模式-模板方法模式
- 设计模式--模板方法模式
- 设计模式-模板方法模式
- 设计模式------模板方法模式
- 设计模式----模板方法模式
- LeetCode 121-123 Best Time to Buy and Sell Stock I II III
- navacat for mysql注册
- 定时清理windows磁盘 只删包含特定字符的目录但不删除文件
- Django中的template的for循环可以用到的。
- GitFlow工作流使用总结
- 设计模式-模板方法模式
- function and pointer
- present viewcontroller 出来的h5调用相册问题
- HDU2216 Game III
- 【Linux】如何克隆虚拟机
- 删除字符串中重复字符。
- 我的树
- 如何安装和使用battery-historian
- webshell的NTFS交换数据流文件隐藏及Python脚本查杀