C++/CLI 版類別適配器,利用多重繼承:TriangleDrawAdapter 同時繼承 IDrawStrategy 與 Triangle。
ref class TriangleDrawAdapter : public IDrawStrategy, public Triangle {
public:
virtual void draw() { paint(); }
};
#include "stdafx.h"
using namespace System;
interface class IDrawStrategy { void draw(); };
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 TriangleDrawAdapter : public IDrawStrategy, public Triangle { public: virtual void draw() { paint(); } };
ref class CircleDrawAdapter : public IDrawStrategy, public Circle { public: virtual void draw() { paint(); } };
ref class SquareDrawAdapter : public IDrawStrategy, public Square { public: virtual void draw() { paint(); } };
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; }
};
int main() {
Grapher^ grapher = gcnew Grapher(gcnew TriangleDrawAdapter());
grapher->drawShape();
grapher->setShape(gcnew CircleDrawAdapter());
grapher->drawShape();
grapher->setShape(gcnew SquareDrawAdapter());
grapher->drawShape();
}
C++/CLI 支援多重繼承(介面與 ref class),適合實作類別適配器;後續將展示 Template 版改良,消除類別爆炸問題。