模板方法模式 详解 设计模式
// 抽象类
abstract class Beverage {
// 模板方法,定义了算法的骨架
public final void prepareBeverage() {
boilWater();
brew();
pourInCup();
addCondiments();
}
// 抽象方法,由子类实现
abstract void brew();
abstract void addCondiments();
// 公共方法,由父类实现
void boilWater() {
System.out.println("Boiling water");
}
void pourInCup() {
System.out.println("Pouring into cup");
}
}
// 具体类1
class Coffee extends Beverage {
@Override
void brew() {
System.out.println("Dripping coffee through filter");
}
@Override
void addCondiments() {
System.out.println("Adding sugar and milk");
}
}
// 具体类2
class Tea extends Beverage {
@Override
void brew() {
System.out.println("Steeping the tea");
}
@Override
void addCondiments() {
System.out.println("Adding lemon");
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Beverage coffee = new Coffee();
coffee.prepareBeverage();
System.out.println();
Beverage tea = new Tea();
tea.prepareBeverage();
}
}