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

我的設計模式之旅[3]:運用 Template 改良 Strategy Pattern (C++)

     編輯:關於C語言

在先前的實作中,IShape 介面的 draw() 方法強制綁定 Grapher 型別,導致若未來有其他類別(如 Painter)想複用這些策略,卻因缺乏繼承或多型關係而無法使用。為解決此耦合問題,我們引入 C++ Template,將介面泛型化,使任何符合條件的型別皆可傳入策略中。

核心改良:泛型化 IShape 介面

將原本固定的 Grapher 參數替換為模板參數 T:

template <typename T>
class IShape {
public:
    virtual void draw(T &grapher) const = 0;
};

如此一來,Triangle、Circle、Square 等具體策略類別也同步改為模板類別,實作 IShape<T>,並在 draw() 中直接呼叫 grapher.getText() 取得繪圖所需文字。

完整程式碼示範

程式碼截圖
#include <iostream>
#include <string>
using namespace std;

class Grapher;

template <typename T>
class IShape {
public:
    virtual void draw(T &grapher) const = 0;
};

class Grapher {
private:
    IShape<Grapher> *shape;
    string text;
public:
    Grapher() {}
    Grapher(IShape<Grapher> *shape, const char* text = "Hello Shape!!") 
        : shape(shape), text(string(text)) {}

    void drawShape() {
        this->shape->draw(*this);
    }
    void setShape(IShape<Grapher> *shape, const char* text = "Hello Shape!!") {
        this->text = text;
        this->shape = shape;
    }
    string getText() const { return this->text; }
};

template <typename T>
class Triangle : public IShape<T>) {
public:
    void draw(T &grapher) const {
        cout << "Draw " << grapher.getText() << " in Triangle" << endl;
    }
};

template <typename T>
class Circle : public IShape<T> {
public:
    void draw(T &grapher) const {
        cout << "Draw " << grapher.getText() << " in Circle" << endl;
    }
};

template <typename T>
class Square : public IShape<T> {
public:
    void draw(T &grapher) const {
        cout << "Draw " << grapher.getText() << " in Square" << endl;
    }
};

int main() {
    Grapher theGrapher(&Square<Grapher>());
    theGrapher.drawShape();
    theGrapher.setShape(&Circle<Grapher>(), "Hello C++!!");
    theGrapher.drawShape();
}

執行結果

Draw Hello Shape!! in Square
Draw Hello C++!! in Circle

結語

泛型編程的應用極為廣泛,此例僅示範其在 Strategy Pattern 中的小規模運用。在 OOP 世界裡,Strategy Pattern 常將 *this 傳給策略物件;搭配泛型編程(GP),可大幅提升策略的重用程度,讓介面不再侷限於特定類別,真正實現「依賴抽象,不依賴具體」的設計原則。

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