【问题标题】:Factory method pattern for an embedded system嵌入式系统的工厂方法模式
【发布时间】:2015-04-04 21:43:16
【问题描述】:

我使用基类实现了继承设计

// Msg.hpp
#ifndef __MSG_H_
#define __MSG_H_

#include <iostream>
#include <string>
class Msg {
  public:
    virtual void buildMsg(std::string &msg) = 0;
};
#endif

在我的示例中,两个派生类:

// GoodMorningMsg.hpp
#ifndef __GOOD_MORNING_MSG_H_
#define __GOOD_MORNING_MSG_H_

#include "Msg.hpp"
class GoodMorningMsg : public Msg {
  public:
    void buildMsg(std::string &msg) {
       msg.append("Good Morning");
    };
};
#endif

// GoodEveningMsg.hpp
#ifndef __GOOD_EVENING_MSG_H_
#define __GOOD_EVENING_MSG_H_

#include "Msg.hpp"
class GoodEveningMsg : public Msg {
  public:
    void buildMsg(std::string &msg) {
       msg.append("Good Evning");
    };
};
#endif

为了避免 switch 的需要,我通常会将 GoodMorningMsgGoodEveningMsg 类的实例放在 std::map 对象中并且每次执行相关对象来构建我的消息。

由于我正在为嵌入式系统编写代码,因此我不允许使用动态分配(换句话说,STL 库)。

假设我事先知道我需要创建的实例的大小,我该如何实现通用代码并避免在我的代码中使用开关?

更新 我解决了一个问题,但第二部分仍然开放。 这是我的 main.cpp:

#include <iostream>
#include <map>
#include "Const.hpp"
#include "Msg.hpp"
#include "GoodMorningMsg.hpp"
#include "GoodEveningMsg.hpp"

void printMsg( std::map<std::string, Msg*> msgMapObject , std::string msg , const std::string & strToFind ) {
    std::map<std::string, Msg*>::iterator it = msgMapObject.find( strToFind );
    if(it != msgMapObject.end()) {
        it->second->buildMsg( msg );
        std::cout << "Message: " << msg << std::endl;
    }
}

int main() {
    GoodMorningMsg goodMorningMsg = GoodMorningMsg();
    GoodEveningMsg goodEveningMsg = GoodEveningMsg();

    std::map<std::string, Msg*> msgMap;

    msgMap.insert(std::make_pair( std::string("GoodMorning") , &goodMorningMsg ) );
    msgMap.insert(std::make_pair( std::string("GoodEvening") , &goodEveningMsg ) ) ;

    std::string msg("I wish you ");

    printMsg( msgMap , msg , std::string("GoodMorning") );
    printMsg( msgMap , msg , std::string("GoodEvening") );

    return 0;   
}

而不是每次都创建 GoodMorningMsg 或 GoodEveningMsg 类的实例,我想放置那些等同于 std::map 的东西,但它不能抛出异常,因为我正在为嵌入式系统应用程序编程。

【问题讨论】:

  • 如果你必须在运行时决定,我看不出有任何方法可以避免虚拟调用/动态分配,但我可能是错的(因为我学会了在 C++ 中永远不要说:) ) 如果您在编译时决定,那么您可以使用多种技术,可能使用标签是最好的。

标签: c++ embedded


【解决方案1】:

可能实现一个抽象的 Msg 类。派生所有三个类 Msg、GoodMorningMsg、GoodEveningMsg。将 Msg 类模板化,并在实例化传递 GoodMorningMsg 类或 GoodEveningMsg 类并设计 Msg 类抽象方法以调用传入类型的 buildMsg 方法时。也就是说,我不确定这将如何解决您的问题,那么我又不是确定我完全理解你的问题

【讨论】:

  • 感谢您的回答。 Msg 类是我的基类,GoodMorningMsg 和 GoodEveningMsg 是我的派生类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
相关资源
最近更新 更多