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

我的設計模式之旅[7]:運用泛型改良 Adapter Pattern ISO C++ 與 C++/CLI Template 實作

     編輯:關於C語言

利用 Template 將類別適配器的被適配類別參數化,單一 DrawAdapter<T> 替代多個具體適配器類別。

ISO C++ 版

template<typename T>
class DrawAdapter : public IDrawStrategy, private T {
public:
    virtual void draw() const;
};

template<typename T>
void DrawAdapter<T>::draw() const { paint(); }

客戶端動態指定型別

int main() {
    Grapher grapher(new DrawAdapter<Triangle>());
    grapher.drawShape();
    grapher.setShape(new DrawAdapter<Circle>());
    grapher.drawShape();
    grapher.setShape(new DrawAdapter<Square>());
    grapher.drawShape();
}

C++/CLI 版

template<typename T>
ref class DrawAdapter : public IDrawStrategy, public T {
public:
    virtual void draw();
};

template<typename T>
void DrawAdapter<T>::draw() { paint(); }

執行結果

Draw Triangle
Draw Circle
Draw Square

Template 版本保留類別適配器「繼承被適配類別」的優勢(易於 override),同時消除類別爆炸,客戶端可動態決定具體型別,兼具靜態型別安全與執行期彈性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved