ISO C++ 版物件適配器,使用指標與虛擬函數實作多型。DrawAdapter 持有 IPaint*,draw() 轉呼叫 _adaptee->paint()。
#include <iostream>
using namespace std;
class IDrawStrategy { public: virtual void draw() const = 0; };
class Grapher {
IDrawStrategy* _drawStrategy;
public:
Grapher(IDrawStrategy* ds = 0) : _drawStrategy(ds) {}
void drawShape() const { if (_drawStrategy) _drawStrategy->draw(); }
void setShape(IDrawStrategy* ds) { _drawStrategy = ds; }
};
class IPaint { public: virtual void paint() const = 0; };
class Triangle : public IPaint { public: void paint() const { cout << "Draw Triangle" << endl; } };
class Circle : public IPaint { public: void paint() const { cout << "Draw Circle" << endl; } };
class Square : public IPaint { public: void paint() const { cout << "Draw Square" << endl; } };
class DrawAdapter : public IDrawStrategy {
IPaint* _adaptee;
public:
DrawAdapter(IPaint* adaptee = 0) : _adaptee(adaptee) {}
virtual void draw() const { _adaptee->paint(); }
};
int main() {
Grapher grapher(new DrawAdapter(new Triangle()));
grapher.drawShape();
grapher.setShape(new DrawAdapter(new Circle()));
grapher.drawShape();
grapher.setShape(new DrawAdapter(new Square()));
grapher.drawShape();
}
注意:範例為簡化未處理記憶體釋放,實務上應使用智慧指標管理生命週期。