Elegant way to implement extensible factories in C++

前端 未结 7 1074
刺人心
刺人心 2020-12-07 14:50

I am looking for an intuitive and extensible way to implement factories for subclasses of a given base class in c++. I want to provide such a factory function in a library.T

7条回答
  •  余生分开走
    2020-12-07 15:32

    Simple solution is just a switch-case:

    Base *create(int type, std::string data) {
      switch(type) { 
       case 0: return new Derived1(data); 
       case 1: return new Derived2(data);
      };
    }
    

    But then it's just deciding which type you want:

       int type_of_obj(string s) {
          int type = -1;
          if (isderived1(s)) type=0;
          if (isderived2(s)) type=1;
          return type;
       } 
    

    Then it's just connecting the two:

    Base *create_obj(string s, string data, 
                     Base *(*fptr)(int type, string data), 
                     int (*fptr2)(string s)) 
    {
       int type = fptr2(s);
       if (type==-1) return 0;
       return fptr(type, data);   
    }
    

    Then it's just registering the function pointers:

       class Registry {
       public:
           void push_back(Base* (*fptr)(int type, string data),
                          int (*fptr2)(string s));
           Base *create(string s, string data);
       };
    

    The plugin will have the 2 functions, and the following:

    void register_classes(Registry ®) {
        reg.push_back(&create, &type_of_obj);
        ...
    }
    

    Plugin loader will dlopen/dlsym the register_classes functions.

    (on the other hand, I'm not using this kind of plugins myself because creating new plugins is too much work. I have better way to provide modularity for my program's pieces. What kills plugins is the fact that you need to modify your build system to create new dll's or shared_libs, and doing that is just too much work - ideally new module is just one class; without anything more complicated build system modifications)

提交回复
热议问题