template
class Grapher {
private: T _drawTemplate;
public: void drawShape() const { _drawTemplate.draw(); }
};
class Triangle { public: void draw() const { cout << "Draw Triangle" << endl; } };
class Circle { public: void draw() const { cout << "Draw Circle" << endl; } };
class Square { public: void draw() const { cout << "Draw Square" << endl; } };
int main() {
Grapher grapher; grapher.drawShape();
Grapher grapher2; grapher2.drawShape();
}
Draw Square
Draw Circle
| 特性 | OOP Strategy | C++ Template | C# Generics |
|---|---|---|---|
| 多態時機 | 運行期 (動態繫結) | 編譯期 (靜態繫結) | 編譯期 (靜態繫結) |
| 介面需求 | 需要介面 | 不需要 (鴨子類型) | 需要介面約束 |
| 運行期變換 | 支援 | 不支援 | 不支援 |
| 程式碼膨脹 | 無 | 有 (每種類型實例化) | 有 (每種類型實例化) |
| 指標/引用 | 需要 (多態) | 物件而非指標 | 物件而非指標 |
C# 2.0 引入泛型後,同樣可用 Generics 實現 Strategy Pattern (見前文)。