高大上的设计模式--什么是模板方法模式
设计模式--分离共同点
咖啡和茶不同,抽象出‘饮料’
把水煮沸
泡的方式不同,抽象成‘泡’
加的调料不同,抽想成‘调料’
Pattern.js
var Coffee=function(){};
Coffee.prototype.boilWater=function(){
console.log("把水煮沸")
};
Coffee.prototype.brewCoffee=function(){
console.log("用沸水冲泡咖啡")
};
Coffee.prototype.pourInCup=function(){
console.log("把咖啡倒进杯子")
};
Coffee.prototype.addSugarAndMilk=function(){
console.log("加糖和牛奶")
};
Coffee.prototype.init=function(){
this.boilWater()
this.brewCoffee()
this.pourInCup()
this.addSugarAndMilk()
};
var Tea=function(){};
Tea.prototype.boilWater=function(){
console.log("把水煮沸")
};
Tea.prototype.steepTea=function(){
console.log("用沸水浸泡茶叶")
};
Tea.prototype.pourInCup=function(){
console.log("把茶水倒进杯子")
};
Tea.prototype.addLemon=function(){
console.log("加柠檬")
};
Tea.prototype.init=function(){
this.boilWater();
this.steepTea();
this.pourInCup();
this.addLemon();
};
var coffee=new Coffee();
coffee.init();
var tea=new Tea();
tea.init();
ctrl+D统一修改
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.addSomething = function() {
throw new Error("子类必须重写该方法");
};
Beverage.prototype.ifWantSometihng=function(){
retuen true;
}
//init是模板方法
Beverage.prototype.init = function() {
this.boilWater();
this.brew();
this.pourInCup();
if(this.ifWantSometihng()){
this.addSomething();
}
};
//--------子类1
var Coffee = function() {};
Coffee.prototype.brew = function() {
console.log("冲咖啡");
};
Coffee.prototype.pourInCup = function() {
console.log("装杯");
};
Coffee.prototype.addSomething = function() {
console.log("加糖");
};
//重写ifWantSometihng方法
Coffee.prototype.ifWantSometihng=function(){
return window.confirm("加不加?");
};
//--------子类2
var Tea = function() {};
Tea.prototype.brew = function() {
console.log("泡茶");
};
Tea.prototype.pourInCup = function() {
console.log("装杯");
};
Tea.prototype.addSomething = function() {
console.log("加柠檬");
};
//继承父类
Coffee.prototype= new Beverage();
Tea.prototype= new Beverage();
var coffee = new Coffee();
coffee.init();
var tea = new Tea();
tea.init();