模板方法模式:定义算法骨架,子类实现具体步骤
// 抽象类
abstract class CoffeeShop {
// 模板方法定义算法骨架
public final void makeCoffee() {
boilWater();
brewCoffee();
pourInCup();
addCondiments();
}
// 基本方法:煮沸水
protected abstract void boilWater();
// 基本方法:冲泡咖啡
protected abstract void brewCoffee();
// 基本方法:倒入杯子
private void pourInCup() {
System.out.println("Pouring coffee into a cup.");
}
// 钩子方法:添加调料
protected void addCondiments() {
System.out.println("Adding sugar and milk.");
}
}
// 具体子类:美式咖啡
class Americano extends CoffeeShop {
@Override
protected void boilWater() {
System.out.println("Boiling water for Americano.");
}
@Override
protected void brewCoffee() {
System.out.println("Brewing Americano coffee.");
}
}
// 具体子类:拿铁
class Latte extends CoffeeShop {
@Override
protected void boilWater() {
System.out.println("Boiling water for Latte.");
}
@Override
protected void brewCoffee() {
System.out.println("Brewing Latte coffee.");
}
@Override
protected void addCondiments() {
System.out.println("Adding milk foam.");
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
CoffeeShop shop = new Americano();
shop.makeCoffee(); // 制作美式咖啡
shop = new Latte();
shop.makeCoffee(); // 制作拿铁
}
}