如何将模板方法模式应用于设计?
摘要:引言 模板方法模式(Template Method Pattern)是一种行为型设计模式。它定义算法骨架,将具体步骤延迟到子类实现。适用于固定流程但部分步骤可变的情景,如游戏初始化或数据处理。 定义 抽象类:定义模板方法(final方法)和
引言
模板方法模式(Template Method Pattern)是一种行为型设计模式。它定义算法骨架,将具体步骤延迟到子类实现。适用于固定流程但部分步骤可变的情景,如游戏初始化或数据处理。
定义
抽象类:定义模板方法(final方法)和抽象步骤。
具体子类:实现抽象步骤。
优点:代码复用,易扩展。缺点:子类过多时复杂。
classDiagram
class Beverage {
+prepare(): void
+boilWater(): void
+pourInCup(): void
+brew(): void abstract
+addCondiments(): void abstract
}
class Coffee {
+brew(): void
+addCondiments(): void
}
class Tea {
+brew(): void
+addCondiments(): void
}
Beverage <|-- Coffee
Beverage <|-- Tea
TypeScript 示例
假设实现饮料冲泡流程。
类实现
// 抽象类
abstract class Beverage {
// 模板方法
prepare(): void {
this.boilWater();
this.brew();
this.pourInCup();
this.addCondiments();
}
boilWater(): void {
console.log("煮沸水");
}
abstract brew(): void; // 抽象步骤
pourInCup(): void {
console.log("倒入杯中");
}
abstract addCondiments(): void; // 抽象步骤
}
// 具体子类:咖啡
class Coffee extends Beverage {
brew(): void {
console.log("冲泡咖啡");
}
addCondiments(): void {
console.log("加糖和奶");
}
}
// 具体子类:茶
class Tea extends Beverage {
brew(): void {
console.log("浸泡茶叶");
}
addCondiments(): void {
console.log("加柠檬");
}
}
// 使用
const coffee = new Coffee();
coffee.prepare(); // 输出:煮沸水 冲泡咖啡 倒入杯中 加糖和奶
const tea = new Tea();
tea.prepare(); // 输出:煮沸水 浸泡茶叶 倒入杯中 加柠檬
prepare() 是模板方法,固定流程。子类重写 brew() 和 addCondiments(),不改整体结构。
