Template Method Pattern C++ 經典虛函數實現:煮飲料流程標準化與子類別客製化
核心代碼
class DrinkMachine {
public: void makeDrink();
protected:
void boilWater() { cout << "boil some water" << endl; }
virtual void doPutIngredient() const = 0;
virtual void doPourInCup() const = 0;
virtual void doAddFlavoring() const = 0;
};
void DrinkMachine::makeDrink() {
this->boilWater();
this->doPutIngredient();
this->doPourInCup();
this->doAddFlavoring();
}
class TeaMachine : public 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 {
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* theDrinkMachine = &TeaMachine(); theDrinkMachine->makeDrink();
cout << "\nMaking Coffee" << endl;
theDrinkMachine = &CoffeeMachine(); theDrinkMachine->makeDrink();
}
執行結果
Making Tea
boil some water
steep tea in boiling water
pour tea in cup
add lemon
Making Coffee
boil some water
brew coffee in boiling water
pour coffee in cup
add sugar and milk.