Java设计模式(七) 模板模式-使用钩子

时间:2023-03-09 13:15:56
Java设计模式(七) 模板模式-使用钩子

1,模板类

package com.pattern.template;

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;
} }

2,模板的子类实现类

package com.pattern.template;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; public class CoffeeWithHook extends CaffeineBeverageWithHook{ /**
* @see com.pattern.template.CaffeineBeverageWithHook#brew()
*/
@Override
void brew() {
System.out.println("Dripping Coffee through filter");
} /**
* @see com.pattern.template.CaffeineBeverageWithHook#addCondiments()
*/
@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 Exception!");
} if(answer == null){
return "no";
}
return answer;
} }

3,测试类

package com.pattern.template;

public class BeverageTestDrive {

	public static void main(String[] args) {

		CoffeeWithHook coffeeHook = new CoffeeWithHook();
System.out.println("\nMaking tea...");
coffeeHook.prepareRecipe();
}
}

4,输出结果:

Making tea...

Boiling water

Dripping Coffee through filter

Pouring into cup

Would you like milk and sugar with your coffee (y/n)?

y

Adding Sugar and Milk