标签:设计模式
描述:类图:
以下程序模拟制作不同饮料的过程。
1.定义有咖啡因的饮料抽象类
package net.dp.templatemethod.barista; 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 net.dp.templatemethod.barista; public class Tea extends CaffeineBeverage { public void brew() { System.out.println("Steeping the tea"); } public void addCondiments() { System.out.println("Adding Lemon"); } }
package net.dp.templatemethod.barista; public class Coffee extends CaffeineBeverage { public void brew() { System.out.println("Dripping Coffee through filter"); } public void addCondiments() { System.out.println("Adding Sugar and Milk"); } }
package net.dp.templatemethod.barista; public class BeverageTestDrive { public static void main(String[] args) { Tea tea = new Tea(); Coffee coffee = new Coffee(); System.out.println("\nMaking tea..."); tea.prepareRecipe(); System.out.println("\nMaking coffee..."); coffee.prepareRecipe(); } }
标签:设计模式
原文地址:http://blog.csdn.net/liuchangqing123/article/details/43938645