首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

我的 Design Pattern 之旅 [2]:Template Method Pattern (2) - C++ 經典實現

     編輯:關於C語言

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.
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved