c++ - 带模板的 C++ 策略模式

标签 c++ templates strategy-pattern

这是 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 要求.这是编译错误的原因。

其次,与模板无关,您无缘无故地多次使用动态分配的对象。我会改变 doSomethingdoAlgorithm按值返回,例如

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/

相关文章:

c++ - 如何从类中访问函数?

c++ - 在执行外部操作时如何避免使用 dynamic_cast?

c++ - 如何在特定位置使用 switch 或 if-else 步骤将十六进制值分配给数组?

c++ - 不允许函数模板部分特化 'swap<T>'

php - 如何在 Smarty(PHP) 中检查复杂条件

java - 访客模式和策略模式之间的区别?

c# - 如何在 C# 中使用泛型实现策略模式

C++ 使用命名空间声明

C# Sitecore 获取继承模板

ios - 如今,数据密集型 iOS 应用程序中普遍接受的加载模式是什么?