设计模式之模板模式

什么是模板模式模板方法模式是一种只需使用继承就可以实现的非常简单的模式。 模板方法模式由两部分结构组成,第一部分是抽象父类,第二部分是具体的实现子类。通常在抽

什么是模板模式

模板方法模式是一种只需使用继承就可以实现的非常简单的模式。
模板方法模式由两部分结构组成,第一部分是抽象父类,第二部分是具体的实现子类。通常在抽象父类中封装了子类的算法框架,包括实现一些公共方法以及封装子类中所有方法的执行顺序。子类通过继承这个抽象类,也继承了整个算法结构,并且可以选择重写父类的方法。

模板模式例子: 傻强,嚯茶还是coffee

泡咖啡的步骤:

(1) 把水煮沸
(2) 用沸水冲泡咖啡
(3) 把咖啡倒进杯子
(4) 加糖和牛奶

var Coffee = function(){};
Coffee.prototype.boilWater = function(){
 console.log( '把水煮沸' );
};
Coffee.prototype.brewCoffeeGriends = function(){
 console.log( '用沸水冲泡咖啡' );
};
Coffee.prototype.pourInCup = function(){
 console.log( '把咖啡倒进杯子' );
};
Coffee.prototype.addSugarAndMilk = function(){
 console.log( '加糖和牛奶' );
};
Coffee.prototype.init = function(){
 this.boilWater();
 this.brewCoffeeGriends();
 this.pourInCup();
 this.addSugarAndMilk();
};
var coffee = new Coffee();
coffee.init(); 

泡茶的步骤:

(1) 把水煮沸
(2) 用沸水浸泡茶叶
(3) 把茶水倒进杯子
(4) 加柠檬

var Tea = function(){};
Tea.prototype.boilWater = function(){
 console.log( '把水煮沸' );
};
Tea.prototype.steepTeaBag = function(){
 console.log( '用沸水浸泡茶叶' );
};
Tea.prototype.pourInCup = function(){
 console.log( '把茶水倒进杯子' );
};
Tea.prototype.addLemon = function(){
 console.log( '加柠檬' );
};
Tea.prototype.init = function(){
 this.boilWater();
 this.steepTeaBag();
 this.pourInCup();
 this.addLemon();
};
var tea = new Tea();
tea.init(); 

分离公共的点


经过抽象之后,不管是泡咖啡还是泡茶,我们都能整理为下面四步:

(1) 把水煮沸
(2) 用沸水冲泡饮料
(3) 把饮料倒进杯子
(4) 加调料

var Beverage = function(){};
Beverage.prototype.boilWater = function(){
 console.log( '把水煮沸' );
};
Beverage.prototype.brew = function(){}; // 空方法,应该由子类重写
Beverage.prototype.pourInCup = function(){}; // 空方法,应该由子类重写
Beverage.prototype.addCondiments = function(){}; // 空方法,应该由子类重写
Beverage.prototype.init = function(){
 this.boilWater();
 this.brew();
 this.pourInCup();
 this.addCondiments();
}; 

创建 Coffee 子类和 Tea 子类

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(); 

小结

模板方法模式是一种典型的通过封装变化提高系统扩展性的设计模式。在传统的面向对象语言中,一个运用了模板方法模式的程序中,子类的方法种类和执行顺序都是不变的,所以我们把这部分逻辑抽象到父类的模板方法里面。而子类的方法具体怎么实现则是可变的,于是我们把这部分变化的逻辑封装到子类中。通过增加新的子类,我们便能给系统增加新的功能,并不需要改动抽象父类以及其他子类,这也是符合开放封闭原则的。但在 JavaScript 中,我们很多时候都不需要依样画瓢地去实现一个模版方法模式,高阶函数是更好的选择。