也就是說,C#不允許繼承泛型,CLI的語言C#、VB、C++/CLI的Generics都無法用這個技巧,但C#卻可用『組合泛型』的方式完成。
C# by Generics
/**//*
(C) OOMusou 2007 http://oomusou.cnblogs.com
Filename : DP_AdpaterPattern_Strategy_ClassByGenerics.cs
Compiler : Visual Studio 2005 / C# 2.0
Description : Demo how to use Strategy Pattern with Adpater Pattern (Class Adapter) By Template
Release : 07/11/2007 1.0
*/
using System;
interface IDrawStrategy {
void draw();
}
class Grapher {
protected IDrawStrategy _drawStrategy;
public Grapher() { }
public Grapher(IDrawStrategy drawStrategy) {
_drawStrategy = drawStrategy;
}
public void drawShape() {
if (_drawStrategy != null)
_drawStrategy.draw();
}
public void setShape(IDrawStrategy drawStrategy) {
_drawStrategy = drawStrategy;
}
}
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
55行
class DrawAdapter<T> : IDrawStrategy where T : IPaint, new() {
protected T _adaptee = new T();
public void draw() {
_adaptee.paint();
}
}