## 模式定義:
? ? ? 模板方法模式在一個方法中定義了一個算法的骨架,而將一些步驟延遲到子類中。模板方法使得子類可以在不改變算法結構的情況下,重新定義算法中的某些步驟。
? ? ? 模板就是一個方法。更具體的說,這個方法將算法定義成一組步驟,其中的任何步驟都可以是抽象的,由子類實現。這可以確保算法的結果保持不變,同時由子類提供部分實現。
## 模式結構:

## 舉例:
? ? ? 泡咖啡和泡茶步驟與基本相同,定義咖啡和茶的類如下:
~~~
class Coffee
{
public:
void prepareRecipe()
{
boilWater();
brewCoffeeGrinds();
pourInCup();
addSugarAndMilk();
}
void boilWater()
{
cout << "Boiling water" << endl;
}
void brewCoffeeGrinds()
{
cout << "Dripping Coffee through filter" << endl;
}
void pourCup()
{
cout << "Pouring into cup" <<endl;
}
void addSugarAndMilk()
{
cout << "Adding Sugar and Milk" << endl;
}
};
class Tea
{
public:
void prepareRecipe()
{
boilWater();
brewReaBag();
pourInCup();
addLemon();
}
void boilWater()
{
cout << "Boiling water" << endl;
}
void brewReaBag()
{
cout << "Steeping the tea" << endl;
}
void pourCup()
{
cout << "Pouring into cup" <<endl;
}
void addLemon()
{
cout << "Adding Lemon" << endl;
}
};
~~~
? ? ? 可見有兩份沖泡算法中都采用了把水煮沸和把飲料倒入杯子的算法,所以可以把他們放到Coffee和Tea的基類(新定義一個咖啡因類CaffeineBeverage.)中。還有兩個算法并沒有被放入基類,但可以將他們定義新的方法名稱brew()和addCondiments()方法,并在子類中實現。
## UML設計:

## 編程實現及執行結果:
~~~
#include <iostream>
using namespace std;
//定義咖啡因基類
class CaffeineBeverage
{
public:
void prepareRecipe()
{
boilWater();
brew();
pourInCup();
addCondiments();
}
void boilWater()
{
cout << "Boiling water" << endl;
}
void pourInCup()
{
cout << "Pouring into cup" <<endl;
}
virtual void brew(){}
virtual void addCondiments(){}
};
//定義咖啡類
class Coffee : public CaffeineBeverage
{
public:
void brew()
{
cout << "Dripping Coffee through filter" << endl;
}
void addCondiments()
{
cout << "Adding Sugar and Milk" << endl;
}
};
//定義茶類
class Tea : public CaffeineBeverage
{
public:
void brew()
{
cout << "Steeping the tea" << endl;
}
void addCondiments()
{
cout << "Adding Lemon" << endl;
}
};
//客戶代碼
int main()
{
Coffee coffee;
cout << "Making coffee..." << endl;
coffee.prepareRecipe();
cout << endl << endl;
Tea tea;
cout << "Make tea...";
tea.prepareRecipe();
return 0;
}
~~~
執行結果如下:
**Makingcoffee...**
**Boilingwater**
**DrippingCoffee through filter**
**Pouringinto cup**
**AddingSugar and Milk**
****
****
**Maketea...Boiling water**
**Steepingthe tea**
**Pouringinto cup**
**AddingLemon**
**請按任意鍵繼續. . .**
## 設計原則的應用:
? ? ? 好萊塢原則:別調用(打電話)我們,我們會調用你。在好萊塢原則下,我們允許低層組件將自己掛鉤到系統上,但是高層組件會決定什么時候和怎么樣使用這些低層組件。如在模板方法中:當我們設計模板方法模式時,我們告訴子類,“不要調用我們,我們會調用你”。