Example
在(原創) 我的Design Pattern之旅[1]:Strategy Pattern (OO) (Design Pattern) (C?C++) (template) (.NET) (C#)中Grapher使用了Strategy Pattern,為了可動態載入畫Triangle,畫Circle,畫Squre的算法,我們定了IDrawStrategy interface,並且寫了Triangle、Circle、Square三個class實現IDrawStrategy interface,但今天發現在某個framwork/library中(如.NET Framework中的GDI+或DirectX),已經存在畫Triangle、Circle、Square的算法了,所以不需重新自己寫,但因為interface不同,所以Grapher無法使用,且我們又沒有該framework/library的source code,根本無法修改成實現IDrawStrategy interface(如我們根本沒有DirectX或.Net Framework的source code),所以我們只好寫一個DrawAdapter,讓Grapher可以使用之。
Class Adapter
IDrawStrategy interface定的是draw(),但IPaint interface定的是paint(),所以Grapher無法使用,因為無法修改IPaint interface和Triangle class、Circle class、Square class(因為可能在其他Framework內,無source code可修改),所以只好加上TriangleDrawAdapter,CircleDrawAdapter和SquareDrawAdapter做轉換。
ISO C++
/**//*
(C) OOMusou 2007 http://oomusou.cnblogs.com
Filename : DP_AdpaterPattern_Strategy_Class.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 (Class).
Release : 07/15/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 TriangleDrawAdapter : public IDrawStrategy, private Triangle {
public:
virtual void draw() const;
};
void TriangleDrawAdapter::draw() const {
paint();
}
class CircleDrawAdapter : public IDrawStrategy, private Circle {
public:
virtual void draw() const;
};
void CircleDrawAdapter::draw() const {
paint();
}
class SquareDrawAdapter : public IDrawStrategy, private Square {
public:
virtual void draw() const;
};
void SquareDrawAdapter::draw() const {
paint();
}
int main() {
Grapher grapher(&TriangleDrawAdapter());
grapher.drawShape();
grapher.setShape(&CircleDrawAdapter());
grapher.drawShape();
grapher.setShape(&SquareDrawAdapter());
grapher.drawShape();
}