【模板模式】在一个方法中定义了一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。
1,定义模板类
package com.pattern.template; public abstract class CaffeineBeverage { final void prepareRecipe(){ 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"); } }
2,定义模板的子类实现类
package com.pattern.template; public class Coffee extends CaffeineBeverage{ /** * @see com.pattern.template.CaffeineBeverage#brew() */ @Override void brew() { System.out.println("Dripping Coffee through filter"); } /** * @see com.pattern.template.CaffeineBeverage#addCondiments() */ @Override void addCondiments() { System.out.println("Adding Sugar and Milk"); } }
package com.pattern.template; public class Tea extends CaffeineBeverage{ /** * @see com.pattern.template.CaffeineBeverage#brew() */ @Override void brew() { System.out.println("Steeping the tea"); } /** * @see com.pattern.template.CaffeineBeverage#addCondiments() */ @Override void addCondiments() { System.out.println("Adding Lemon"); } }
3,测试类
package com.pattern.template; public class BeverageTestDrive { public static void main(String[] args) { Coffee coffee = new Coffee(); coffee.prepareRecipe(); } }
运行结果如下:
Boiling water
Dripping Coffee through filter
Pouring into cup
Adding Sugar and Milk
类图如下所示: