工厂可以通过查找特定文件以某种方式确定所有可能的类吗? [英] Can a factory somehow determine all possible classes, by looking in a particular file?

查看:118
本文介绍了工厂可以通过查找特定文件以某种方式确定所有可能的类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

For example, given a specific file where users are constantly adding derived classes:

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]...

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

Can a Factory generate a list of possible classes to map to, based on their name?

 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;
     }
 };

推荐答案

您可以编写一个解析器并使类处理输入文件,但是我怀疑那是您想要的.

You can write a parser and have the class process the input file, but I doubt that's what you want.

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

You can also use the crtp pattern to your advantage:

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();

然后您将派生类为

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

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

This would automatically register your class with Factory given its name (you have to implement name in non-abstract classes because it's pure).

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

Additionally, you can pass a callback to registerClass that knows how to create your derived class.

这篇关于工厂可以通过查找特定文件以某种方式确定所有可能的类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆