设计模式-模板方法模式

来源:互联网 发布:mac哪个适合唇色深的 编辑:程序博客网 时间:2024/06/01 07:11

1.描述:模板方法模式是一种只需要使用继承就可以实现的非常简单的模式,模式由两部分组成-抽象父类和具现子类。通常在抽象父类中封装了子类的算法框架。

2.实例:Coffee or Tea

父类-饮料-步骤:

  1. 把水煮沸
  2. 用沸水冲泡饮料
  3. 把饮料倒进杯子
  4. 加调料
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();