定义:模板方法定义了一个算法的步骤,并且允许子类重载某些步骤。
使用场景:算法的总体步骤基本稳定,但是某些步骤的具体算法经常改变
类图:
代码样例:
package headfirst.templatemethod.barista;
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;
}
}
package headfirst.templatemethod.barista;
import java.io.*;
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;
}
}
优点:1)规范化算法步骤,总体框架趋于稳定,防止代码五花八门,便于大家理解代码;2)抽象出总体步骤,减少开发者思考时间,提升开发效率 3)
缺点:1)模板方法改变,所有的子类都可能会受影响
类似的设计模式:
见工厂方法设计模式
配套的内功心法:1)好莱坞原则:不要找我,我会找你;即让高层次代码决定何时调用低层次代码,而低层次代码实现具体的算法以组成具体系统。