3

这是 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()'
4

2 回答 2

6

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

其次,与模板无关,您可以无缘无故地使用动态分配的对象。例如,我会更改doSomething并按doAlgorithm值返回

OtherObject doSomething(const OtherObject &obj);

并从 main 中删除所有用途new,例如:

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

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

于 2012-06-25T15:15:54.043 回答
0

将算法封装在类层次结构中,让该算法的客户端持有指向该层次结构的基类的指针,并将对该算法的所有请求委托给该“匿名”包含的对象,称为策略模式

于 2016-07-26T07:10:56.717 回答