HeadFirst设计模式-模板方法模式
模板方法模式:在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。
package h_TemplateMethodPattern; 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"); } } //---------------------- package h_TemplateMethodPattern; public class Coffee extends CaffeineBeverage { @Override void brew() { System.out.println("Dripping Coffee through filter."); } @Override void addCondiments() { System.out.println("Adding Sugar and Milk"); } } //---------------------- package h_TemplateMethodPattern; public class Tea extends CaffeineBeverage { @Override void brew() { System.out.println("Stepping the tea"); } @Override void addCondiments() { System.out.println("Adding Lemon"); } } //---------------------- package h_TemplateMethodPattern; public class TestDemo { public static void main(String[] args) { Tea tea = new Tea(); tea.prepareRecipe(); System.out.println("--------------------------"); Coffee coffee = new Coffee(); coffee.prepareRecipe(); } }
***
常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。
昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。