这是 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. }
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;
}
主要.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()'
最佳答案
首先,类模板实现应该放在头文件或头文件包含的文件中,而不是放在要编译的 .cpp 文件中。编译器需要查看模板代码才能创建 MyContext<ConcreteStrategy>
main
要求.这是编译错误的原因。
其次,与模板无关,您无缘无故地多次使用动态分配的对象。我会改变 doSomething
和 doAlgorithm
按值返回,例如
OtherObject doSomething(const OtherObject &obj);
并删除所有对 new
的使用来自 main,例如:
int main(int argc,char **argv) {
OtherObject obj;
MyContext<ConcreteStrategy> aContext;
obj = aContext.doAlgorithm(obj);
return 0;
}
如果你真的必须使用动态分配的对象,那么我建议使用 smart pointers ,特别是 C++11 的 std::unique_ptr .
关于c++ - 带模板的 C++ 策略模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11191447/