從UML可以發現,TriangleDrawAdapter、CircleDrawAdapter和SquareDrawAdapter都不見了,只剩下一個DrawAdapter,為什麽可以這樣子呢?因為Class Adapter的致命傷就是得繼承Adaptee,這是很強的coupling,利用泛型,我們將繼承的class變成泛型的參數
70行
template<typename T>
class DrawAdapter : public IDrawStrategy, private T {
public:
virtual void draw() const;
};
這樣就可以在ClIEnt動態的以Adaptee為泛型參數傳入Class Adapter
int main() {
Grapher grapher(&DrawAdapter<Triangle>());
grapher.drawShape();
grapher.setShape(&DrawAdapter<Circle>());
grapher.drawShape();
grapher.setShape(&DrawAdapter<Square>());
grapher.drawShape();
}
C++/CLI
/**//*
(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/12/2007 1.0
*/
#include "stdafx.h"
using namespace System;
interface class IDrawStrategy {
void draw();
};
ref class Grapher {
public:
Grapher() : _drawStrategy(nullptr) {}
Grapher(IDrawStrategy^ drawStrategy) : _drawStrategy(drawStrategy) {}
public:
void drawShape();
void setShape(IDrawStrategy^ drawStrategy);
protected:
IDrawStrategy^ _drawStrategy;
};
void Grapher::drawShape() {
if (_drawStrategy != nullptr)
_drawStrategy->draw();
}
void Grapher::setShape(IDrawStrategy^ drawStrategy) {
_drawStrategy = drawStrategy;
}
interface class IPaint {
void paint();
};
ref class Triangle : public IPaint {
public:
virtual void paint();
};
void Triangle::paint() {
Console::WriteLine("Draw Triangle");
}
ref class Circle : public IPaint {
public:
virtual void paint();
};
void Circle::paint() {
Console::WriteLine("Draw Circle");
}
ref class Square : public IPaint {
public:
virtual void paint();
};
void Square::paint() {
Console::WriteLine("Draw Square");
}
template<typename T>
ref class DrawAdapter : public IDrawStrategy, public T {
public:
virtual void draw();
};
template<typename T>
void DrawAdapter<T>::draw() {
paint();
}
int main() {
Grapher^ grapher = gcnew Grapher(gcnew DrawAdapter<Triangle>);
grapher->drawShape();
grapher->setShape(gcnew DrawAdapter<Circle>);
grapher->drawShape();
grapher->setShape(gcnew DrawAdapter<Square>);
grapher->drawShape();
}
執行結果
Draw Triangle
Draw Circle
Draw Square