定义
模板方法模式由两部分结构组成,第一部分是抽象父类,第二部分是具体的实现子类。通常在抽象父类中封装了子类的算法框架,包括实现一些公共方法以及封装子类中所有方法的执行顺序。子类通过继承这个抽象类,也继承了整个算法结构,并且可以选择重写父类的方法。——《JavaScript设计模式与开发实践》
其中最重要的两点是:
1、可被子类选择复写的公共方法。
2、封装所有方法的执行顺序。
实现示例
const Beverage = function( param ){
const boilWater = function(){
console.log( '把水煮沸' );
};
const brew = param.brew || function(){
throw new Error( '必须传递brew 方法' );
};
const pourInCup = param.pourInCup || function(){
throw new Error( '必须传递pourInCup 方法' );
};
const addCondiments = param.addCondiments || function(){
throw new Error( '必须传递addCondiments 方法' );
};
const F = function(){};
F.prototype.init = function(){
boilWater();
brew();
pourInCup();
addCondiments();
};
return F;
};
// 使用示例
const Coffee = Beverage({
brew: function(){
console.log( '用沸水冲泡咖啡' );
},
pourInCup: function(){
console.log( '把咖啡倒进杯子' );
},
addCondiments: function(){
console.log( '加糖和牛奶' );
}
});
const Tea = Beverage({
brew: function(){
console.log( '用沸水浸泡茶叶' );
},
pourInCup: function(){
console.log( '把茶倒进杯子' );
},
addCondiments: function(){
console.log( '加柠檬' );
}
});
const coffee = new Coffee();
coffee.init();
const tea = new Tea();
tea.init();
使用场景
父类将方法的执行顺序封装起来,而将具体的方法交由子类去实现。这样的模式我们可以在各种框架中看到,比如vue的生命周期函数、vue-router的导航守卫等等。