javascript设计模式13模板方法
模板方法模式,是众多设计模式中,为数不多的依赖继承的一种设计模式。需要一个抽象类,封装子类的算法框架和方法的执行顺序,子类继承父类之后,父类通知子类执行这些方法。父类的通知方法,即是模板方法。
模板方法模式是一种典型的通过封装变化提高系统扩展性的模式。
// 传统的面向对象语言的继承方式
var Beverage = function(){
}
Beverage.prototype.boilWater = function(){
console.log('煮水')
}
Beverage.prototype.brew = function(){
throw new Error('子类实现')
}
Beverage.prototype.pourInCup = function(){
throw new Error('子类实现')
}
Beverage.prototype.addCondiments = function(){
throw new Error('子类实现')
}
Beverage.prototype.init = function(){
this.boilWater()
this.brew()
this.pourInCup()
this.addCondiments()
}
var coffee = function()
coffee.prototype = new Beverage();
coffee.brew = function(){
console.log('冲coffee')
}
coffee.pourInCup = function(){
console.log('倒coffee')
}
coffee.addCondiments = function(){
console.log('加糖和牛奶')
}
// javascript中的灵活的实现方式,高阶函数
var Beverage = function(param){
var boilWater = function(){
console.log('冲水')
}
var brew = param.brew || function(){
throw new Error('子类实现')
}
var pourInCup = param.pourInCup || function(){
throw new Error('子类实现')
}
var addCondiments = param.addCondiments || function(){
throw new Error('子类实现')
}
var F = function(){}
F.prototype.init = function(){
boilWater()
brew()
pourInCup()
addCondiments()
}
return F;
}
var coffee = Beverage({
brew:function(){
console.log('coffee')
},
pourInCup:function(){
console.log('coffee')
},
addCondiments:function(){
console.log('cofee')
}
})
var coffee = new coffee()
coffee.init()
Think Different, Make Different-编程是一个习惯

浙公网安备 33010602011771号