How to implement the factory method pattern in C++ correctly

后端 未结 11 1071
暗喜
暗喜 2020-11-22 14:55

There\'s this one thing in C++ which has been making me feel uncomfortable for quite a long time, because I honestly don\'t know how to do it, even though it sounds simple:<

11条回答
  •  伪装坚强ぢ
    2020-11-22 15:21

    You can read a very good solution in: http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus

    The best solution is on the "comments and discussions", see the "No need for static Create methods".

    From this idea, I've done a factory. Note that I'm using Qt, but you can change QMap and QString for std equivalents.

    #ifndef FACTORY_H
    #define FACTORY_H
    
    #include 
    #include 
    
    template 
    class Factory
    {
    public:
        template 
        void registerType(QString name)
        {
            static_assert(std::is_base_of::value, "Factory::registerType doesn't accept this type because doesn't derive from base class");
            _createFuncs[name] = &createFunc;
        }
    
        T* create(QString name) {
            typename QMap::const_iterator it = _createFuncs.find(name);
            if (it != _createFuncs.end()) {
                return it.value()();
            }
            return nullptr;
        }
    
    private:
        template 
        static T* createFunc()
        {
            return new TDerived();
        }
    
        typedef T* (*PCreateFunc)();
        QMap _createFuncs;
    };
    
    #endif // FACTORY_H
    

    Sample usage:

    Factory f;
    f.registerType("Descendant1");
    f.registerType("Descendant2");
    Descendant1* d1 = static_cast(f.create("Descendant1"));
    Descendant2* d2 = static_cast(f.create("Descendant2"));
    BaseClass *b1 = f.create("Descendant1");
    BaseClass *b2 = f.create("Descendant2");
    

提交回复
热议问题