我的Design Pattern之旅[7]:使用泛型改進Adapter Pattern(OO)2010-03-29 cnblogs Introduction在(原创) 我的Design Pattern之旅[6] : Adapter Pattern (OO) (Design Pattern) (C/C++) (.NET) (C#) (C++/CLI) (VB) 中的Grapher范例,我们看到Class Adapter必须针对Triangle、Circle、Square量身订做TriangleDrawAdapter、CircleDrawAdapter、SquareDrawAdapter,虽然符合OCP,但每个class就得需要专属的Adapter,会造成class爆炸,本文试着用泛型来解决此问题。

ISO C++
/**//*
(C) OOMusou 2007 http://oomusou.cnblogs.com
Filename : DP_AdpaterPattern_Strategy_ClassByTemplate.cpp
Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
Description : Demo how to use Strategy Pattern with Adpater Pattern (Class Adapter) By Template
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;
}
template<typename T>
class DrawAdapter : public IDrawStrategy, private T {
public:
virtual void draw() const;
};
template<typename T>
void DrawAdapter<T>::draw() const {
paint();
}
int main() {
Grapher grapher(&DrawAdapter<Triangle>());
grapher.drawShape();
grapher.setShape(&DrawAdapter<Circle>());
grapher.drawShape();
grapher.setShape(&DrawAdapter<Square>());
grapher.drawShape();
}
执行结果
Draw Triangle
Draw Circle
Draw Square