模板方法模式是一种行为设计模式,它定义了一个算法的框架,将某些步骤的具体实现延迟到子类中。模板方法模式通过定义一个抽象基类,其中包含了算法的主要结构和步骤,但其中某些具体步骤的实现由子类来决定。这样可以保持算法的整体结构稳定,同时允许各个子类根据自身特性进行定制化的实现。
模板方法模式的主要思想是:将算法的通用部分放在父类中,而将具体实现细节留给子类来实现。这样可以使代码更具可维护性、可扩展性和可复用性。
TypeScript 实现
以下是一个简单的模板方法模式的示例,假设我们要制作咖啡和茶:
abstract class Beverage {
prepareRecipe(): void {
this.boilWater();
this.brew();
this.pourInCup();
this.addCondiments();
}
boilWater(): void {
console.log("Boiling water");
}
abstract brew(): void;
abstract addCondiments(): void;
pourInCup(): void {
console.log("Pouring into cup");
}
}
class Coffee extends Beverage {
brew(): void {
console.log("Dripping coffee through filter");
}
addCondiments(): void {
console.log("Adding sugar and milk");
}
}
class Tea extends Beverage {
brew(): void {
console.log("Steeping the tea");
}
addCondiments(): void {
console.log("Adding lemon");
}
}
const coffee = new Coffee();
coffee.prepareRecipe();
const tea = new Tea();
tea.prepareRecipe();
在这个示例中,Beverage 是抽象基类,其中定义了制作饮料的通用步骤(如烧水、冲泡、倒入杯子、添加调料)。子类 Coffee 和 Tea 分别继承了 Beverage,并实现了具体的冲泡和调料添加步骤。
通过模板方法模式,我们可以确保制作饮料的主要流程在父类中统一定义,而具体的实现细节在子类中进行定制,实现了代码的复用和扩展。
JavaScript 实现
class Beverage {
prepareRecipe() {
this.boilWater();
this.brew();
this.pourInCup();
this.addCondiments();
}
boilWater() {
console.log("Boiling water");
}
pourInCup() {
console.log("Pouring into cup");
}
brew() {}
addCondiments() {}
}
class Coffee extends Beverage {
brew() {
console.log("Dripping coffee through filter");
}
addCondiments() {
console.log("Adding sugar and milk");
}
}
class Tea extends Beverage {
brew() {
console.log("Steeping the tea");
}
addCondiments() {
console.log("Adding lemon");
}
}
const coffee = new Coffee();
coffee.prepareRecipe();
const tea = new Tea();
tea.prepareRecipe();