C# 版類別適配器:TriangleDrawAdapter 繼承 Triangle 並實作 IDrawStrategy。C# 單一繼承限制,僅能繼承一個類別,故適配器必須繼承具體類別而非介面。
class TriangleDrawAdapter : Triangle, IDrawStrategy {
public void draw() { paint(); }
}
using System;
interface IDrawStrategy { void draw(); }
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 TriangleDrawAdapter : Triangle, IDrawStrategy { public void draw() { paint(); } }
class CircleDrawAdapter : Circle, IDrawStrategy { public void draw() { paint(); } }
class SquareDrawAdapter : Square, IDrawStrategy { public void draw() { paint(); } }
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; }
}
class Client {
static void Main() {
Grapher grapher = new Grapher(new TriangleDrawAdapter());
grapher.drawShape();
grapher.setShape(new CircleDrawAdapter());
grapher.drawShape();
grapher.setShape(new SquareDrawAdapter());
grapher.drawShape();
}
}
C# 不支援多重繼承類別,類別適配器只能繼承具體類別,導致每個具體類別都需對應一個適配器子類別,這是類別適配器在 C# 的固有限制。