带有模板的C++策略模式

2 c++ templates strategy-pattern

这是C++中Strategy Pattern的示例实现:

ConcreteStrategy.h

class ConcreteStrategy {
public:
    ConcreteStrategy();
    ~ConcreteStrategy();
    const OtherObject* doSomething(const OtherObject &obj);
};
Run Code Online (Sandbox Code Playgroud)

ConcreteStrategy.cpp

#include "ConcreteStrategy.h"

ConcreteStrategy::ConcreteStrategy() { // etc. }
ConcreteStrategy::~ConcreteStrategy() { // etc. }
const OtherObject* ConcreteStrategy::doSomething(const OtherObject &obj) { // etc. }
Run Code Online (Sandbox Code Playgroud)

MyContext.h

template <class Strategy> class MyContext {
    public:
        MyContext();
        ~MyContext();
        const OtherObject* doAlgorithm(const OtherObject &obj);
    private:
        Strategy* _the_strategy;
};
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

这种实施是对的吗?这是我与C++模板第一种方法,我已经有些怀疑,特别是有关上下文(MyContext)内建设和模板对象(战略)的破坏.

更新:我在编译时遇到此错误:

undefined reference to `MyContext<Strategy>::MyContext()'
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 5

首先,类模板实现应该放在头文件中或头文件所包含的文件中,而不是要编译的.cpp文件中.编译器需要查看模板代码才能创建MyContext<ConcreteStrategy>所需的main.这是编译器错误的原因.

其次,与模板无关,你有很多动态分配对象的用法,没有明显的原因.例如,我会改变doSomething并按doAlgorithm值返回

OtherObject doSomething(const OtherObject &obj);
Run Code Online (Sandbox Code Playgroud)

并删除newmain 中的所有用法,例如:

int main(int argc,char **argv) {
    OtherObject obj;
    MyContext<ConcreteStrategy> aContext;
    obj = aContext.doAlgorithm(obj);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果你真的必须使用动态分配的对象,那么我建议使用智能指针,特别是C++ 11的std :: unique_ptr.