在先前的實作中,IShape 介面的 draw() 方法強制綁定 Grapher 型別,導致若未來有其他類別(如 Painter)想複用這些策略,卻因缺乏繼承或多型關係而無法使用。為解決此耦合問題,我們引入 C++ Template,將介面泛型化,使任何符合條件的型別皆可傳入策略中。
將原本固定的 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),可大幅提升策略的重用程度,讓介面不再侷限於特定類別,真正實現「依賴抽象,不依賴具體」的設計原則。