Factory Pattern in C++: generating explicit createInstance()-Method automatically

家住魔仙堡 提交于 2019-12-09 02:14:31

I can't imagine a way to create this automatically without any coding per part of the user. I can imagine ways to simplify it, perhaps using a macro:

#define OBJECT_CREATOR(X) \
    extern "C" {          \
         BaseClass *UserXCreateInstance() {\
             return new X(); \
         }\
    }

And the user just need to put on his cpp file:

OBJECT_CREATOR(UserClass);

I'll assume calling the user function via dlsym is not an absolute requirement.

What you want is easy to achieve by using CRTP. A constructor of a static helper object then registers relevant data in a central repository. It should go like this:

template <typename UserClass>
class BaseClass
{
  private:
    class UserObjectFactory
    {
      UserObjectFactory()
      {
        std::string myname = typeid(UserClass).name();
        CentralObjectFactory::instance()->register(this, myname);
      }
      BaseClass* XUserCreateInstance()
      {
        return new UserClass;
      }            
    };
    static UserObjectFactory factory; 
};

Users code is simple:

class MyClass : public BaseClass<MyClass>
{
  // whatever
};

Presumably, the CentralObjectFactory instance contains some kind of (multi)map from std::string to UserObjectFactory.

myname could be initialized to some uniquely generated string instead of typeid(UserClass).name(), in order to avoid collisions.

If all you need is a single object of each user's class, you can make UserObjectFactory create an instance of UserClass and register it instead.

   std::string myname = typeid(UserClass).name();
   CentralObjectRepository::instance()->register(XUserCreateInstance(), myname);

Does this design fulfil your needs?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!