这是 C++ 中策略模式的示例实现:
具体策略.h
class ConcreteStrategy {
public:
ConcreteStrategy();
~ConcreteStrategy();
const OtherObject* doSomething(const OtherObject &obj);
};
具体策略.cpp
#include "ConcreteStrategy.h"
ConcreteStrategy::ConcreteStrategy() { // etc. }
ConcreteStrategy::~ConcreteStrategy() { // etc. }
const OtherObject* ConcreteStrategy::doSomething(const OtherObject &obj) { // etc. }
我的上下文.h
template <class Strategy> class MyContext {
public:
MyContext();
~MyContext();
const OtherObject* doAlgorithm(const OtherObject &obj);
private:
Strategy* _the_strategy;
};
我的上下文.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;
}
主文件
#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()'