C++/CLI
/**//*
(C) OOMusou 2007 http://oomusou.cnblogs.com
Filename : DP_AdpaterPattern_Strategy_Class.cpp
Compiler : Visual C++ 8.0 / C++/CLI
Description : Demo how to use Strategy Pattern with Adapter Pattern (Class)
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");
}
ref class TriangleDrawAdapter : public IDrawStrategy, public Triangle {
public:
virtual void draw();
};
void TriangleDrawAdapter::draw() {
paint();
}
ref class CircleDrawAdapter : public IDrawStrategy, public Circle {
public:
virtual void draw();
};
void CircleDrawAdapter::draw() {
paint();
}
ref class SquareDrawAdapter : public IDrawStrategy, public Square {
public:
virtual void draw();
};
void SquareDrawAdapter::draw() {
paint();
}
int main() {
Grapher^ grapher = gcnew Grapher(gcnew TriangleDrawAdapter);
grapher->drawShape();
grapher->setShape(gcnew CircleDrawAdapter);
grapher->drawShape();
grapher->setShape(gcnew SquareDrawAdapter);
grapher->drawShape();
}