** The Template Method Pattern ** defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
** 模版方法模式 ** 在一個方法中定義了算法的基本框架和結(jié)構(gòu),然后將部分具體的步驟留給子類去具體實現(xiàn)。模版方法模式允許子類去自定義自己的算法的特定的步驟,但是又不改變整體的算法的結(jié)構(gòu),這樣就可以實現(xiàn)代碼的復(fù)用。
下面我們就通過一個簡單的實例來講講什么是模版方法模式?
假設(shè)我們需要制作一杯咖啡和一杯茶,首先我們看看制作咖啡的幾個簡單的步驟:
- boilWater
- brewCoffeeGrinds
- pourInCup
- addSugarAndMilk
同時我們看看制作一杯茶所需要的步驟:
- boilWater
- steepTeaBag
- pourInCup
- addLemon
我們發(fā)現(xiàn)制作茶和咖啡的基本步驟有兩步是一樣的,如果我們直接實現(xiàn),也就是各實現(xiàn)各的算法,那么顯然,會產(chǎn)生重復(fù)的代碼,也就是boilWater和pourInCup是重復(fù)的。
public class Coffee {
void prepareRecipe() {
boilWater();
brewCoffeeGrinds();
pourInCup();
addSugarAndMilk();
}
public void boilWater() {
System.out.println(“Boiling water”);
}
public void brewCoffeeGrinds() {
System.out.println(“Dripping Coffee through fi lter”);
}
public void pourInCup() {
System.out.println(“Pouring into cup”);
}
public void addSugarAndMilk() {
System.out.println(“Adding Sugar and Milk”);
}
}
public class Tea {
void prepareRecipe() {
boilWater();
steepTeaBag();
pourInCup();
addLemon();
}
public void boilWater() {
System.out.println(“Boiling water”);
}
public void steepTeaBag() {
System.out.println(“Steeping the tea”);
}
public void addLemon() {
System.out.println(“Adding Lemon”);
}
public void pourInCup() {
System.out.println(“Pouring into cup”);
}
}
我們顯然可以想到一個簡單的方法就是設(shè)計一個超類將重復(fù)的兩個方法封裝起來,這樣子類就不用實現(xiàn)了,只需要繼承超類的方法即可。
但這樣其實還不夠好,我們仔細觀察,可以發(fā)現(xiàn),制作茶和咖啡不同的兩個步驟,我們可以抽象為超類中的一個方法,并設(shè)置為抽象方法,讓子類去對應(yīng)的實現(xiàn)自己的相應(yīng)方法,這樣就更好的封裝和復(fù)用。
我們定義一個超類:
public abstract class CaffeineBeverage {
final void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}
abstract void brew();
abstract void addCondiments();
void boilWater() {
System.out.println(“Boiling water”);
}
void pourInCup() {
System.out.println(“Pouring into cup”);
}
}
我們可以看到我們將算法的步驟封裝在prepareRecipe,為了不讓子類去修改這個方法,我們設(shè)置為final,同時對于子類公用的方法,我們直接在超類中實現(xiàn),這樣子類直接調(diào)用即可,對于需要不同實現(xiàn)的特定方法,我們在超類中定義一個抽象方法,讓子類去自己實現(xiàn)。
這樣子類的代碼就變的很簡潔,因為只要實現(xiàn)兩個抽象方法
public class Tea extends CaffeineBeverage {
public void brew() {
System.out.println(“Steeping the tea”);
}
public void addCondiments() {
System.out.println(“Adding Lemon”);
}
}
public class Coffee extends CaffeineBeverage {
public void brew() {
System.out.println(“Dripping Coffee through filter”);
}
public void addCondiments() {
System.out.println(“Adding Sugar and Milk”);
}
}
模版方法模式定義了算法的步驟,同時允許子類去自定義的實現(xiàn)其中的一個或者多個步驟
模版方法模式為一個算法創(chuàng)造一個實現(xiàn)的模版。什么是模版呢?
就是一個算法需要實現(xiàn)的一系列步驟,這些步驟可以分別用一系列的方法封裝起來。在模版方法中,部分這些方法定義為抽象的,由具體的子類去實現(xiàn),這樣就保證了雖然可能實現(xiàn)不同,但是整體的算法框架是不變的,都需要經(jīng)過相同的步驟。
我們考慮一種情況,即有時候,子類可能并不需要實現(xiàn)模版方法中定義的全部方法,可能其中一個方法,有的子類需要實現(xiàn),有的子類卻不需要實現(xiàn),那么我們該如何解決這樣的需求問題呢?
** 使用hook **
public abstract class CaffeineBeverageWithHook {
final 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;
}
}
即增加一個方法,通常返回bool類型的變量對是否使用進行判斷。我們形象的稱它為鉤子,hook
其中的子類一種實現(xiàn)的例子,如下:
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;
}
}
這樣用戶可以更靈活的控制,通過鉤子是否調(diào)用其中的某個方法。
hook就是起到這樣的作用,它使得子類的可以更靈活的選擇某些超類模版方法中的方法。
策略模式和模版方法模式在某些程度上是很相似的,但策略模式是為了避免繼承,采用接口,組合的形式,而模版方法模式是通過繼承實現(xiàn)的
同時,沃恩也可以發(fā)現(xiàn),工廠模式其實就是模版方法模式的一種,特殊的模版方法模式,專用于創(chuàng)建新的對象。