interface IDrawStrategy { void draw(); }
class Grapher {
private IDrawStrategy _drawStrategy = null;
public Grapher() {}
public Grapher(IDrawStrategy drawStrategy) { _drawStrategy = drawStrategy; }
public void drawShape() { if (_drawStrategy != null) _drawStrategy.draw(); }
public void setShape(IDrawStrategy 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(new Square());
grapher.drawShape();
grapher.setShape(new Circle());
grapher.drawShape();
}
}
Draw Square
Draw Circle
介面是最正規 OOP 寫法。Effective C++ Item 35 亦使用函數指標實現 Strategy,屬 C/C++ 獨有寫法。