标签:
钩子的还有一个使用方法,是让子类能够有机会对模板方法中某些即将发生的(或刚刚发生的)步骤做出反应。
//声明为抽象类,子类必须实现其操作 public abstract class CaffeineBeverage { //声明为final,不希望子类覆盖这种方法 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"); } } //extends继承 public class Tea extends CaffeineBeverage { //须要定义抽象方法 public void brew() { System.out.println("Steeping the tea"); } public void addCondiments() { System.out.println("Adding Lemon"); } }
public abstract class CaffeineBeverageWithHook { void prepareRecipe() { boilWater(); brew(); pourInCup(); if (customerWantsCondiments()) { addCondiments(); } } abstract void brew(); abstract void addCondiments(); void boilWater() { System.out.println("Boiling water"); } void pourInCup() { System.out.println("Pouring into cup"); } //定义了一个缺省实现,子类能够覆盖它。但不见得一定要这么做 boolean customerWantsCondiments() { return true; } } public class CoffeeWithHook extends CaffeineBeverageWithHook { public void brew() { System.out.println("Dripping Coffee through filter"); } public void addCondiments() { System.out.println("Adding Sugar and Milk"); } //覆盖了这种方法。提供了自己的功能 public boolean customerWantsCondiments() { //让用户输入对调料的决定 String answer = getUserInput(); if (answer.toLowerCase().startsWith("y")) { return true; } else { return false; } } private String getUserInput() { String answer = null; System.out.print("Would you like milk and sugar with your coffee (y/n)? "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { answer = in.readLine(); } catch (IOException ioe) { System.err.println("IO error trying to read your answer"); } if (answer == null) { return "no"; } return answer; } }
标签:
原文地址:http://www.cnblogs.com/mengfanrong/p/5177887.html