【问题标题】:Can a factory somehow determine all possible classes, by looking in a particular file?工厂可以通过查看特定文件以某种方式确定所有可能的类吗?
【发布时间】:2014-06-30 20:45:03
【问题描述】:

是否可以根据特定文件中指定的所有类创建一个在运行时生成所有派生类(和类名)的工厂?

例如,给定一个用户不断添加派生类的特定文件:

class Laptop: public Computer {
  public:
     virtual void Run(){mHibernating = false;}
     virtual void Stop(){mHibernating = true;}
 private:
     bool mHibernating; // Whether or not the machine is hibernating
 };

class Desktop: public Computer {
 public:
     virtual void Run(){mOn = true;}
     virtual void Stop(){mOn = false;}
 private:
     bool mOn; // Whether or not the machine has been turned on
 };

// ....[more classes derived from Computer]...

工厂能否根据名称生成可能映射到的类列表?

 class ComputerFactory {
 public:
     static Computer *NewComputer(const std::string &description)
     {
         if(description == "Laptop")
             return new Laptop;
         } else if (description == "Desktop") {
             return new Desktop;
         } else if  // ...[more comparisons based on the classes defined at runtime]...
         } else return NULL;
     }
 };

【问题讨论】:

  • 如果源文件中没有一些附加信息,这是不可能的。通常的做法是有一个宏REGISTER_TYPE,以某种方式提供相关信息,然后到REGISTER_TYPE(Laptop)REGISTER_TYPE(Computer)等。
  • 为什么不断向文件中添加类的相同用户也不能维护所述地图?
  • @sgarza62 简短的回答是否定的。您可以编写一个外部工具来查看文件内部并识别它具有的类。该工具可以为您生成工厂。
  • @StoryTeller 我同意;你是对的。我在一个 HTTP 服务器上工作,我们被要求使用一个配置文件,用户将 URI(作为正则表达式)与派生的 HttpRequestHandler 类相关联。因此,将根据请求的 URI 调用特定的处理程序。

标签: c++ c++11 polymorphism factory derived-class


【解决方案1】:

您可以编写一个解析器并让类处理输入文件,但我怀疑这就是您想要的。

您还可以使用 crtp 模式来发挥自己的优势:

template<class T>
struct Base
{
   Base()
   { 
      reg;
   }
   virtual std::string name() = 0;
   static bool reg;
   static bool init() 
   { 
      T t; 
      Factory::registerClass(t.name());
      return true;
   }
};

template<class T>
bool Base<T>::reg = Base<T>::init();

source

然后你将类派生为

struct Derived1 : Base<Derived1> 
{
 ...
}

这将自动注册您的类,并使用给定名称的Factory(您必须在非抽象类中实现name,因为它是纯粹的)。

此外,您可以将回调传递给知道如何创建派生类的registerClass

【讨论】:

    猜你喜欢
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多