系列第四篇開啟 C# 版本探討。C# 2.0 引入 Generics,嘗試將 C++ Template 版 Strategy Pattern 移植。核心概念相同:為讓策略完整存取 Context 物件,將 this 傳給策略的 draw() 方法。
interface IShape {
void draw(Grapher grapher);
}
Grapher 持有 IShape 參考,drawShape() 呼叫 shape.draw(this)。策略類別(Triangle、Circle、Square)實作 IShape,在 draw() 中取得 grapher.getText()。
using System;
interface IShape {
void draw(Grapher grapher);
}
class Grapher {
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 {
public void draw(Grapher grapher) {
Console.WriteLine("Draw {0:s} in Triangle", grapher.getText());
}
}
class Circle : IShape {
public void draw(Grapher grapher) {
Console.WriteLine("Draw {0:s} in Circle", grapher.getText());
}
}
class Square : IShape {
public void draw(Grapher grapher) {
Console.WriteLine("Draw {0:s} in Square", grapher.getText());
}
}
class MainClass {
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 仍綁定 Grapher 型別,若新增 Painter 類別欲複用策略將無法編譯。下篇將引入 Generic 解決。