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

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

     編輯:關於C語言

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