これは、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;
}
この実装は正しいですか?これはC++でのテンプレートを使用した最初のアプローチであり、特にコンテキスト(MyContext)内のテンプレートオブジェクト(Strategy)の構築と破棄については疑問があります。
更新:コンパイル時にこのエラーが発生しました:
undefined reference to `MyContext<Strategy>::MyContext()'