System.out.println("-------泡茶咯----------");
System.out.println("-------煮咖啡咯----------");
Coffee myCoffee = new Coffee();
myCoffee.prepareRecipe();
System.out.println("-------煮咖啡咯----------");
}
}
package simpleTamplateMethod;
public class CaffineBeverageTest {
public static void main(String[] args) {
System.out.println("-------泡茶咯----------");
Tea myTea = new Tea();
myTea.prepareRecipe(); //调用模板方法,就这样把所有工作做完了
System.out.println("-------泡茶咯----------");
System.out.println("-------煮咖啡咯----------");
Coffee myCoffee = new Coffee();
myCoffee.prepareRecipe();
System.out.println("-------煮咖啡咯----------");
}
}
测试结果
-------泡茶咯----------
Boiling water
Steeping the tea
Pouring into cup
Adding Lemon
-------泡茶咯----------
-------煮咖啡咯----------
Boiling water
Dripping Coffee through filter
Pouring into cup
Adding Sugar and Milk
-------煮咖啡咯----------
对模板方法进行挂钩
[java]
package hook;
/**
* 模块方法使用钩子
* @author wwj
*
*/
public abstract class CaffineBeverageWithHook {
void prepareRecipe() {
boilWater();
brew();
pourInCup();
if(customerWantsCondiments()){ //加上这个条件,通过一个具体方法来决定是否执行语句,这就是对模块方法进行挂钩
addCondiments();
}
}
abstract void brew();
abstract void addCondiments();
void boilWater() {
System.out.println("Boilng water");
}
void pourInCup() {
System.out.println("Pouring into cup");
}
/**
* 这就是钩子
* @return
*/
boolean customerWantsCondiments() {
return true;
}
}
package hook;
/**
* 模块方法使用钩子
* @author wwj
*
*/
public abstract class CaffineBeverageWithHook {
void prepareRecipe() {
boilWater();
brew();
pourInCup();
if(customerWantsCondiments()){ //加上这个条件,通过一个具体方法来决定是否执行语句,这就是对模块方法进行挂钩
addCondiments();
}
}
abstract void brew();
abstract void addCondiments();
void boilWater() {
System.out.println("Boilng water");
}
void pourInCup() {
System.out.println("Pouring into cup");
}
/**
* 这就是钩子
* @return
*/
boolean customerWantsCondiments() {
return true;
}
}
[java]
package hook;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CoffeeWithHook extends CaffineBeverageWithHook {
@Override
void brew() {
System.out.println("Dripping Coffee through filter");
}
@Override
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.println("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 e) {
System.out.println("IO error trying t