核心提示:设计模式-模板方法模式。1.描述:模板方法模式是一种只需要使用继承就可以实现的非常简单的模式,模式由两部分组成-抽象父类和具现子类。通常在抽象父类中封装了子类的算法框架。2.实例:Coffee or ...
设计模式-模板方法模式。
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(); } } //子类coffee var 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();