模版方法模式在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中,模版方法使得子类可以在不改变算法结构的情况下,重新定义算法的某些步骤。
示例—咖啡与茶
咖啡店冲咖啡与泡茶的方法分别是:
冲咖啡:
(1). 把水煮沸
(2). 用沸水冲泡咖啡
(3). 把咖啡倒进杯子
(4). 加糖和牛奶
泡茶
(1). 把水煮沸
(2). 用沸水浸泡茶叶
(3). 把茶倒进杯子
(4). 加柠檬
合并重复代码,并抽象出基类。
UML图表示
代码演示
咖啡因饮料基类
package Template;
public abstract class CaffeineBeverage {
final void prepareRecipe (){
boilWater();
brew();
pourInCup();
if (customerWantsCondiments()){
addCondiments();
}
}
abstract void brew();
abstract void addCondiments();
final void boilWater() {
System.out.println("Boiling water");
}
final void pourInCup() {
System.out.println("Pouring into cup");
}
/**
* 钩子方法,子类覆盖这个方法,但不见得一定要这么做
* @return
*/
boolean customerWantsCondiments(){
return true;
}
}
咖啡
package Template;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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");
}
@Override
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 e) {
System.err.println("IO error trying to read your answer");
}
if (answer == null) {
return "no";
}
return answer;
}
}
茶
package Template;
public class Tea extends CaffeineBeverage {
@Override
void brew() {
System.out.println("Steeping the tea");
}
@Override
void addCondiments() {
System.out.println("Adding Lemon");
}
}
测试代码
package Template;
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();
}
}
测试结果
Making tea...
Boiling water
Steeping the tea
Pouring into cup
Adding Lemon
Making coffee...
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