Template Method Pattern C++ Template 實現:CRTP 靜態多態消除虛函數開銷
核心代碼 (Quark 提供)
template
class DrinkMachine {
public:
void makeDrink() {
T* derived = (T*)this;
this->boilWater();
derived->doPutIngredient();
derived->doPourInCup();
derived->doAddFlavoring();
}
protected:
void boilWater() { cout << "boil some water" << endl; }
};
class TeaMachine : public DrinkMachine {
friend DrinkMachine;
protected:
void doPutIngredient() const { cout << "steep tea in boiling water" << endl; }
void doPourInCup() const { cout << "pour tea in cup" << endl; }
void doAddFlavoring() const { cout << "add lemon" << endl; }
};
class CoffeeMachine : public DrinkMachine {
friend DrinkMachine;
protected:
void doPutIngredient() const { cout << "brew coffee in boiling water" << endl; }
void doPourInCup() const { cout << "pour coffee in cup" << endl; }
void doAddFlavoring() const { cout << "add sugar and milk." << endl; }
};
int main() {
cout << "Making Tea" << endl;
DrinkMachine* pTeaMachine = &TeaMachine();
pTeaMachine->makeDrink();
cout << "\nMaking Coffee" << endl;
DrinkMachine* pCoffeeMachine = &CoffeeMachine();
pCoffeeMachine->makeDrink();
}
Strategy vs Template Method 核心差異
- 目的相同:對新需求不同演算法提供擴充機制
- 手法不同:Strategy 用物件委派 (運行期可變),Template Method 用類別繼承 (編譯期固定)
- GoF 原文:Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.