C++/CLI 版本展示相同架構:Grapher 使用 IDrawStrategy,既有繪圖類別實作 IPaint,透過 DrawAdapter(物件適配器)橋接兩介面。
interface class IDrawStrategy { void draw(); };
interface class IPaint { void paint(); };
ref class DrawAdapter : public IDrawStrategy {
IPaint^ _adaptee;
public:
DrawAdapter(IPaint^ adaptee) : _adaptee(adaptee) {}
virtual void draw() { _adaptee->paint(); }
};
#include "stdafx.h"
using namespace System;
interface class IDrawStrategy { void draw(); };
ref class Grapher {
IDrawStrategy^ _drawStrategy;
public:
Grapher() : _drawStrategy(nullptr) {}
Grapher(IDrawStrategy^ ds) : _drawStrategy(ds) {}
void drawShape() { if (_drawStrategy != nullptr) _drawStrategy->draw(); }
void setShape(IDrawStrategy^ ds) { _drawStrategy = ds; }
};
interface class IPaint { void paint(); };
ref class Triangle : public IPaint {
public: virtual void paint() { Console::WriteLine("Draw Triangle"); }
};
ref class Circle : public IPaint {
public: virtual void paint() { Console::WriteLine("Draw Circle"); }
};
ref class Square : public IPaint {
public: virtual void paint() { Console::WriteLine("Draw Square"); }
};
ref class DrawAdapter : public IDrawStrategy {
IPaint^ _adaptee;
public:
DrawAdapter() : _adaptee(nullptr) {}
DrawAdapter(IPaint^ adaptee) : _adaptee(adaptee) {}
virtual void draw() { _adaptee->paint(); }
};
int main() {
Grapher^ grapher = gcnew Grapher(gcnew DrawAdapter(gcnew Triangle()));
grapher->drawShape();
grapher->setShape(gcnew DrawAdapter(gcnew Circle()));
grapher->drawShape();
grapher->setShape(gcnew DrawAdapter(gcnew Square()));
grapher->drawShape();
}
C++/CLI 同時支援 ISO C++ Template 與 CLI Generics,是 .NET 語言中泛型能力最強者,後續文章將展示其 Template 版類別適配器改良。