Generic 改進 Strategy Pattern:IGrapher 介面雙向協作與多上下文複用
核心代碼
interface IGrapher { string getText(); }
interface IShape { void draw(T grapher); }
class Grapher : IGrapher {
private IShape shape;
private string text;
public Grapher() {}
public Grapher(IShape shape) : this(shape, "Hello Shape!!") {}
public Grapher(IShape shape, string text) { this.shape = shape; this.text = text; }
public void drawShape() { this.shape.draw(this); }
public void setShape(IShape shape, string text) { this.text = text; this.shape = shape; }
public string getText() { return this.text; }
}
class Triangle : IShape where T : IGrapher {
public void draw(T grapher) { Console.WriteLine("Draw {0:s} in Triangle", grapher.getText()); }
}
class Circle : IShape where T : IGrapher {
public void draw(T grapher) { Console.WriteLine("Draw {0:s} in Circle", grapher.getText()); }
}
class Square : IShape where T : IGrapher {
public void draw(T grapher) { Console.WriteLine("Draw {0:s} in Square", grapher.getText()); }
}
class main {
public static void Main() {
Grapher theGrapher = new Grapher(new Square());
theGrapher.drawShape();
theGrapher.setShape(new Circle(), "Hello C#!!");
theGrapher.drawShape();
}
}
執行結果
Draw Hello Shape!! in Square
Draw Hello C#!! in Circle
改進亮點
IShape 泛型介面,T : IGrapher 約束確保雙向協作
- 策略可透過
grapher.getText() 取得上下文資訊
- 若 Painter 類別也實作
IGrapher,同樣可使用 IShape 策略
- 編譯期類型安全,運行期零裝箱開銷
圖 1:完整程式碼結構截圖