前端设计模式(三):模板方法模式
模板方法模式的定义:在一个方法里定义算法的骨架,将一些步骤延迟到其子类。
意思是用一个方法包装多个函数的调用,这个方法就是模板,函数的使用只需要跟着模板里的步骤进行即可,同时根据情况可以放入钩子函数来选择是否在指定位置执行函数。
假设我们现在要做饮料,做饮料通常有以下步骤:1、烧开水,2、泡东西,3、倒入杯子,4、加调料
那么用代码描述为:
// ts 定义一个接口
interface IMakeDrinks {
/* 烧开水 */
boilWater: () => void;
/* 泡东西 */
brew: () => void;
/* 倒入杯子 */
pourInCup: () => void;
/* 加调料 */
addCondiments: () => void;
/* 初始化方法 */
init: () => void
}
抽象出来一个父类:
/**
* 做饮料父类
*/
class AbstractMakeDrinks implements IMakeDrinks{
isAddCondiments: boolean = false;
constructor(isAddCondiments: boolean) {
this.isAddCondiments = isAddCondiments;
}
addCondiments() {
throw new Error('需要子类实现')
}
boilWater() {
throw new Error('需要子类实现')
}
brew() {
throw new Error('需要子类实现')
}
pourInCup() {
throw new Error('需要子类实现')
}
init() {
this.boilWater();
this.brew();
this.pourInCup();
if(this.isAddCondiments){
this.addCondiments();
}
}
}
具体子类来实现做东西的过程,然后调用父类的init方法搞定
class Coffee extends AbstractMakeDrinks {
boilWater() {
console.log('把白开水烧开')
}
brew() {
console.log('把咖啡和水导入壶里')
}
pourInCup() {
console.log('倒入咖啡杯')
}
addCondiments() {
console.log('加牛奶和糖')
}
}
const coffee = new Coffee(true);
coffee.init();
假设有牛奶饮品,一样的套路。
当做饮料的种类多了,并结合策略模式:
// 结合策略模式
const getDrinks = (type: string) => {
const typeStrategy: any = {
'coffee': new Coffee(true)
}
return typeStrategy[type]
}
const drinkObj = getDrinks('coffee');
drinkObj.init();

浙公网安备 33010602011771号