C# Generics 不支援繼承泛型參數(class DrawAdapter<T> : T 錯誤:Cannot derive from 'T' because it is a type parameter),故採組合方式改良類別適配器。
class DrawAdapter<T> : IDrawStrategy where T : IPaint, new() {
protected T _adaptee = new T();
public void draw() { _adaptee.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 DrawAdapter<T> : IDrawStrategy where T : IPaint, new() {
protected T _adaptee = new T();
public void draw() { _adaptee.paint(); }
}
class Client {
static void Main() {
Grapher grapher = new Grapher(new DrawAdapter<Triangle>());
grapher.drawShape();
grapher.setShape(new DrawAdapter<Circle>());
grapher.drawShape();
grapher.setShape(new DrawAdapter<Square>());
grapher.drawShape();
}
}
Draw Triangle
Draw Circle
Draw Square
單一 DrawAdapter<T> 取代三個具體適配器類別,客戶端以 new DrawAdapter<Triangle>() 指定具體型別,達到類別適配器「單一類別適配多型別」的效果,且保有型別安全。