设计模式-模板方法实现

时间:2025-01-22 10:59:52
// 抽象类:饮品制作流程 abstract class Beverage { // 模板方法:定义饮品制作的算法骨架 public final void prepareRecipe() { boilWater(); brew(); pourInCup(); if (customerWantsCondiments()) { addCondiments(); } } // 公共步骤,所有饮品都需要 private void boilWater() { System.out.println("Boiling water."); } private void pourInCup() { System.out.println("Pouring into cup."); } // 抽象步骤,由子类实现 protected abstract void brew(); protected abstract void addCondiments(); // 钩子方法:提供默认实现,子类可选择覆盖 protected boolean customerWantsCondiments() { return true; } } // 具体类:制作茶 class Tea extends Beverage { @Override protected void brew() { System.out.println("Steeping the tea."); } @Override protected void addCondiments() { System.out.println("Adding lemon."); } } // 具体类:制作咖啡 class Coffee extends Beverage { @Override protected void brew() { System.out.println("Dripping coffee through filter."); } @Override protected void addCondiments() { System.out.println("Adding sugar and milk."); } } // 测试代码 public class TemplateMethodExample { public static void main(String[] args) { System.out.println("Making tea:"); Beverage tea = new Tea(); tea.prepareRecipe(); System.out.println("\nMaking coffee:"); Beverage coffee = new Coffee(); coffee.prepareRecipe(); } }