C# 版物件適配器實作,架構同前:Grapher 依賴 IDrawStrategy,既有類別實作 IPaint,DrawAdapter 組合 IPaint 並轉呼叫 paint()。
using System;
interface IDrawStrategy { void draw(); }
class Grapher {
protected IDrawStrategy _drawStrategy = null;
public Grapher() {}
public Grapher(IDrawStrategy ds) { _drawStrategy = ds; }
public void drawShape() { if (_drawStrategy != null) _drawStrategy.draw(); }
public void setShape(IDrawStrategy ds) { _drawStrategy = ds; }
}
interface IPaint { void paint(); }
class Triangle : IPaint { public void paint() { Console.WriteLine("Draw Triangle"); } }
class Circle : IPaint { public void paint() { Console.WriteLine("Draw Circle"); } }
class Square : IPaint { public void paint() { Console.WriteLine("Draw Square"); } }
class DrawAdapter : IDrawStrategy {
protected IPaint _adaptee = null;
public DrawAdapter() {}
public DrawAdapter(IPaint adaptee) { _adaptee = adaptee; }
public void draw() { _adaptee.paint(); }
}
class Client {
static void Main() {
Grapher grapher = new Grapher(new DrawAdapter(new Triangle()));
grapher.drawShape();
grapher.setShape(new DrawAdapter(new Circle()));
grapher.drawShape();
grapher.setShape(new DrawAdapter(new Square()));
grapher.drawShape();
}
}
Draw Triangle
Draw Circle
Draw Square
物件適配器採用組合而非繼承,單一適配器類別即可處理所有 IPaint 實作,符合「多用組合、少用繼承」原則,且支援執行期動態切換被適配物件。