模板方法模式(行为型)
设计模式的3个分类:创建型模式、结构型模式、行为型模式
模板方法模式(Template Method Pattern)的意图:
模板方法模式是在超类中定义了一个算法的框架, 允许子类在不修改结构的情况下重写算法的特定步骤。
使用场景: 1、有多个子类共有的方法,且逻辑相同。 2、重要的、复杂的方法,可以考虑作为模板方法。
注意事项:为防止恶意操作,一般模板方法都加上 final 关键词。
模板方法模式图示:

(注:实际应用中,不一定需要按照上图首先有一个接口(或更高层次的抽象类),再抽象类和具体实现,可以只有抽象的模板类和具体的实现,灵活运用,抽象程度依据实际情况)
代码实现:
以下是一种带钩子(hook)的举例,通过hook可以增强程序的灵活性。
/**
* 抽象模版
*/
public abstract class CoffeineBeverageWithHook {
final void prepareRecipe() {
boilWater();
brew();
pourInCup();
if (customerWantsCondiments()) {
addCondiments();
}
}
void boilWater() {
System.out.println("Boiling water");
}
void pourInCup() {
System.out.println("Pouring into cup");
}
abstract void brew();
abstract void addCondiments();
protected boolean customerWantsCondiments() {
return true;
}
}
/**
* 继承实现抽象模板,并针对hook添加相应逻辑
*/
public class CoffeeWithHook extends CoffeineBeverageWithHook {
@Override
void brew() {
System.out.println("this is coffee's brew");
}
@Override
void addCondiments() {
System.out.println("this is coffee's addCondiments");
}
@Override
protected 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 to read your answer");
e.printStackTrace();
}
if (answer == null) {
return "no";
}
return answer;
}
}
/**
* 测试
*/
public class CoffeineBevergeUseMain {
public static void main(String[] args) {
CoffeineBeverageWithHook coffeineHook = new CoffeeWithHook();
coffeineHook.prepareRecipe();
}
}
--End

浙公网安备 33010602011771号