var Beverage = function(){
};
Beverage.prototype.boilWater = function(){
console.log("把水煮沸");
}
Beverage.prototype.brew = function(){
throw new Error('子类必须重写brew方法');
};
Beverage.prototype.pourlnCup = function(){
throw new Error('子类必须重写pourlnCup方法');
};
Beverage.prototype.addCondiments = function(){
throw new Error('子类必须重写addCondiments方法');
};
Beverage.prototype.customerWantsCondiments = function(){
// 默认需要调料
return true;
}
Beverage.prototype.init = function(){
this.boilWater();
this.brew();
this.pourlnCup();
// 如果挂钩返回true 则需要调料
if( this.customerWantsCondiments() ){
this.addCondiments();
}
}
// 咖啡
var Coffee = function(){};
Coffee.prototype = new Beverage();
Coffee.prototype.brew = function(){
console.log('用沸水冲泡咖啡');
}
Coffee.prototype.pourlnCup = function(){
console.log('把咖啡倒进杯子');
}
Coffee.prototype.addCondiments = function(){
console.log('加糖和牛奶');
}
var coffee = new Coffee();
coffee.init();
console.log('\n');
// 茶
var Tea = function(){};
Tea.prototype = new Beverage();
Tea.prototype.brew = function(){
console.log('用沸水浸泡茶叶');
}
Tea.prototype.pourlnCup = function(){
console.log('把茶倒进杯子');
}
Tea.prototype.addCondiments = function(){
console.log('加柠檬');
}
var tea = new Tea();
tea.init();
console