Object Adapter
ISO C++
/**//*
(C) OOMusou 2007 http://oomusou.cnblogs.com
Filename : DP_AdpaterPattern_Strategy_Object.cpp
Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
Description : Demo how to use Strategy Pattern with Adapter Pattern (Object)
Release : 07/11/2007 1.0
*/
#include <iOStream>
using namespace std;
class IDrawStrategy {
public:
virtual void draw() const = 0;
};
class Grapher {
public:
Grapher(IDrawStrategy* drawStrategy = 0) : _drawStrategy(drawStrategy) {}
public:
void drawShape() const;
void setShape(IDrawStrategy* drawStrategy);
protected:
IDrawStrategy* _drawStrategy;
};
void Grapher::drawShape() const {
if (_drawStrategy)
_drawStrategy->draw();
}
void Grapher::setShape(IDrawStrategy* drawStrategy) {
_drawStrategy = drawStrategy;
}
class IPaint {
public:
virtual void paint() const = 0;
};
class Triangle : public IPaint {
public:
void paint() const;
};
void Triangle::paint() const {
cout << "Draw Triangle" << endl;
}
class Circle : public IPaint {
public:
void paint() const;
};
void Circle::paint() const {
cout << "Draw Circle" << endl;
}
class Square : public IPaint {
public:
void paint() const;
};
void Square::paint() const {
cout << "Draw Square" << endl;
}
class DrawAdapter : public IDrawStrategy {
public:
DrawAdapter(IPaint* adaptee = 0) : _adaptee(adaptee) {}
virtual void draw() const;
protected:
IPaint* _adaptee;
};
void DrawAdapter::draw() const {
_adaptee->paint();
}
int main() {
Grapher grapher(&DrawAdapter(&Triangle()));
grapher.drawShape();
grapher.setShape(&DrawAdapter(&Circle()));
grapher.drawShape();
grapher.setShape(&DrawAdapter(&Square()));
grapher.drawShape();
}