interface IDrawStrategy { void draw(); }
class Grapher where T : class, IDrawStrategy, new() {
private T _drawStrategy = default(T);
public Grapher() { _drawStrategy = new T(); }
public void drawShape() { if (_drawStrategy != null) _drawStrategy.draw(); }
public void setShape(T drawStrategy) { _drawStrategy = drawStrategy; }
}
class Triangle : IDrawStrategy { public void draw() { Console.WriteLine("Draw Triangle"); } }
class Circle : IDrawStrategy { public void draw() { Console.WriteLine("Draw Circle"); } }
class Square : IDrawStrategy { public void draw() { Console.WriteLine("Draw Square"); } }
class Program {
public static void Main() {
Grapher grapher = new Grapher();
grapher.drawShape();
Grapher grapher2 = new Grapher();
grapher2.drawShape();
}
}
Draw Square
Draw Circle
| 維度 | Strategy (OOP) | Template Method | Generics |
|---|---|---|---|
| 多態實現 | 介面 + 動態繫結 (運行期) | 繼承 + 重寫 (編譯期) | 泛型約束 (編譯期) |
| 運行期變換 | 支援 (setShape) | 不支援 | 不支援 (類型參數固定) |
| 效能 | 虛擬呼叫開銷 | 虛擬呼叫開銷 | 零開銷 (靜態調度) |
GoF 原文:Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.
Known Use:Eclipse Plugin 架構,無需修改核心即可擴充功能。