javascript模版模式
模版模式:利用父类定义一些类似对象的公共方法和操作框架
简单例子
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.prototype.brew = function () {
console.log('用沸水冲泡咖啡');
};
Coffee.prototype.pourInCup = function () {
console.log('把咖啡倒进杯子');
};
Coffee.prototype.addCondiments = function () {
console.log('加糖和牛奶');
};
var coffee = new Coffee();
coffee.init();
/*******泡茶********/
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();
钩子方法
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.customWantsCondiments = function () {
return true;
};
Beverage.prototype.init = function () {
this.boilwater();
this.brew();
this.pourInCup();
if(this.customWantsCondiments()){
this.addCondiments();
}
};
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('加糖和牛奶');
};
Coffee.prototype.customWantsCondiments = function () {
return window.confirm('需要加调料吗?');
};
var coffee = new Coffee();
coffee.init();
使用好莱坞原则
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('用沸水冲泡咖啡');
},
pourInCup: function () {
console.log('把咖啡倒进杯子');
},
addCondiments: function () {
console.log('加糖和牛奶');
}
});
var coffee = new Coffee();
coffee.init();
子类不能调用父类,只能父类调用子类