C#若要使用泛型的method,就得加上constraint,又因為使用delegation的方式,所以必須將泛型new起來,C#規定要在constraint加上new()。
C++/CLI by Generics
/**//*
(C) OOMusou 2007 http://oomusou.cnblogs.com
Filename : DP_AdpaterPattern_Strategy_ClassByGenerics.cs
Compiler : Visual Studio 2005 / C++/CLI
Description : Demo how to use Strategy Pattern with Adpater Pattern (Class Adapter) By Generics
Release : 07/20/2007 1.0
*/
#include "stdafx.h"
using namespace System;
interface class IDrawStrategy {
void draw();
};
ref class Grapher {
public:
Grapher() {}
Grapher(IDrawStrategy^ drawStrategy) : _drawStrategy(drawStrategy) {}
public:
void drawShape();
void setShape(IDrawStrategy^ drawStrategy);
protected:
IDrawStrategy^ _drawStrategy;
};
void Grapher::drawShape() {
if (_drawStrategy != nullptr)
_drawStrategy->draw();
}
void Grapher::setShape(IDrawStrategy^ drawStrategy) {
_drawStrategy = drawStrategy;
}
interface class IPaint {
void paint();
};
ref class Triangle : public IPaint {
public:
virtual void paint();
};
void Triangle::paint() {
Console::WriteLine("Draw Triangle");
}
ref class Circle : public IPaint {
public:
virtual void paint();
};
void Circle::paint() {
Console::WriteLine("Draw Circle");
}
ref class Square : public IPaint {
public:
virtual void paint();
};
void Square::paint() {
Console::WriteLine("Draw Square");
}
generic<typename T>
where T : IPaint, gcnew()
ref class DrawAdapter : public IDrawStrategy {
public:
DrawAdapter() : _adaptee(gcnew T){}
public:
virtual void draw();
protected:
T _adaptee;
};
generic<typename T>
void DrawAdapter<T>::draw() {
_adaptee->paint();
}
int main() {
Grapher^ grapher = gcnew Grapher(gcnew DrawAdapter<Triangle^>);
grapher->drawShape();
grapher->setShape(gcnew DrawAdapter<Circle^>);
grapher->drawShape();
grapher->setShape(gcnew DrawAdapter<Square^>);
grapher->drawShape();
}
執行結果
Draw Triangle
Draw Circle
Draw Square
72行
generic<typename T>
where T : IPaint, gcnew()
ref class DrawAdapter : public IDrawStrategy {
public:
DrawAdapter() : _adaptee(gcnew T){}
public:
virtual void draw();
protected:
T _adaptee;
};