This is a sample implementation of Strategy Pattern in C++:
ConcreteStrategy.h
class ConcreteStrategy {
public:
ConcreteStrategy();
~ConcreteStrategy();
const OtherObject* doSomething(const OtherObject &obj);
};
ConcreteStrategy.cpp
#include "ConcreteStrategy.h"
ConcreteStrategy::ConcreteStrategy() { // etc. }
ConcreteStrategy::~ConcreteStrategy() { // etc. }
const OtherObject* ConcreteStrategy::doSomething(const OtherObject &obj) { // etc. }
MyContext.h
template <class Strategy> class MyContext {
public:
MyContext();
~MyContext();
const OtherObject* doAlgorithm(const OtherObject &obj);
private:
Strategy* _the_strategy;
};
MyContext.cpp
#include "MyContext.h"
template <typename Strategy>
MyContext<Strategy>::MyContext() {
_the_strategy = new Strategy;
}
template <typename Strategy>
MyContext<Strategy>::~MyContext() {
delete _the_strategy;
}
template <typename Strategy>
const OtherObject* MyContext<Strategy>::doAlgorithm(const OtherObject &obj) {
obj = _the_strategy(obj);
// do other.
return obj;
}
main.cpp
#include "MyContext.h"
#include "ConcreteStrategy.h"
#include "OtherPrivateLib.h"
int main(int argc,char **argv) {
OtherObject* obj = new OtherObject;
MyContext<ConcreteStrategy>* aContext = new MyContext<ConcreteStrategy>;
obj = aContext.doAlgorithm(obj);
// etc.
delete aContext;
delete obj;
return 0;
}
Is this implementation right? It's my first approach with template in C++ and I've some doubt, specially about construction and destruction of template object (Strategy) inside the context (MyContext).
UPDATE: I've this error at compile-time:
undefined reference to `MyContext<Strategy>::MyContext()'