模板方法模式在流程标准化场景中的应用解析
业务背景与需求分析
在软件开发中,经常遇到某些业务流程整体框架一致,但具体细节步骤存在差异的场景。例如在一个饮品制作系统中,虽然美式咖啡与拿铁的制作核心流程相似,但在配料环节存在区别。系统需要支持根据用户指令输出对应的制作步骤日志。
具体流程包含三个核心阶段:
- 咖啡豆研磨(Grinding)
- 咖啡萃取(Brewing)
- 配料添加(Customizing)
其中,美式咖啡仅需添加常规调料,而拿铁则需要额外添加牛奶。输入为整数指令(1 代表美式,2 代表拿铁),输出为对应的制作流程文本。
初始实现方案及其局限
若不采用设计模式,通常会直接在主逻辑中使用条件判断语句来处理不同分支。以下是一种典型的面向过程实现方式:
public class BeverageHandler {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
while (input.hasNextInt()) {
int choice = input.nextInt();
if (choice == 1) {
System.out.println("Prepare Americano:");
System.out.println("Grinding beans");
System.out.println("Brewing extract");
System.out.println("Adding sugar");
} else if (choice == 2) {
System.out.println("Prepare Latte:");
System.out.println("Grinding beans");
System.out.println("Brewing extract");
System.out.println("Adding milk");
System.out.println("Adding sugar");
} else {
throw new IllegalArgumentException("Invalid selection");
}
System.out.println();
}
}
}
这种实现方式虽然直观,但存在明显的代码冗余。研磨和萃取步骤在两个分支中完全重复。一旦需要修改通用步骤(例如改变研磨方式的输出文本),必须修改所有分支。此外,随着饮品种类增加,条件分支会越来越复杂,违背了开闭原则。
基于模板方法模式的重构
为了解决上述问题,可以将不变的行为封装在抽象父类中,将可变的行为延迟到子类实现。这正是模板方法模式的核心思想。
1. 定义抽象模板类
创建一个抽象类 AbstractBeverage,定义最终算法骨架 makeRecipe。该方法声明为 final 以防止子类篡改流程顺序。差异步骤定义为钩子方法 addIngredients。
public abstract class AbstractBeverage {
public final void makeRecipe() {
System.out.println("Start Making:");
grindBeans();
brewExtract();
addIngredients();
System.out.println("Finished.\n");
}
private void grindBeans() {
System.out.println("Grinding beans");
}
private void brewExtract() {
System.out.println("Brewing extract");
}
protected void addIngredients() {
System.out.println("Adding sugar");
}
}
2. 实现具体子类
针对不同的饮品类型,继承抽象类并重写配料方法。美式咖啡沿用默认行为,拿铁则需扩展逻辑。
public class Americano extends AbstractBeverage {
// 无需重写,使用默认配料逻辑
}
public class CaffeLatte extends AbstractBeverage {
@Override
protected void addIngredients() {
System.out.println("Adding milk");
System.out.println("Adding sugar");
}
}
3. 客户端调用与注册管理
为了方便管理不同的饮品实例,可以引入一个简单的注册表类来映射指令与具体实现。
import java.util.HashMap;
import java.util.Map;
public class BeverageRegistry {
private final Map registry = new HashMap<>();
public BeverageRegistry() {
registry.put(1, new Americano());
registry.put(2, new CaffeLatte());
}
public void processOrder(int code) {
AbstractBeverage beverage = registry.get(code);
if (beverage != null) {
beverage.makeRecipe();
} else {
throw new RuntimeException("Unknown beverage code: " + code);
}
}
}
主程序通过注册表调用,逻辑更加清晰:
public class Client {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
BeverageRegistry registry = new BeverageRegistry();
while (input.hasNextInt()) {
int selection = input.nextInt();
registry.processOrder(selection);
}
}
}
模式应用的关键考量
在使用模板方法模式时,抽象类定义了算法的骨架,控制了流程的稳定性。子类仅关注具体步骤的实现,实现了代码复用与逻辑解耦。
需要注意的是,抽象类中的通用步骤设计应当足够概括。如果模板定义得过于具体,当某个子类需要特殊流程时,可能会被迫修改父类,从而影响其他子类。因此,合理利用钩子方法(Hook Method)提供扩展点,是保持系统灵活性的关键。通过这种方式,新增饮品种类只需添加新的子类,无需修改现有代码,符合开闭原则。