简单工厂模式扩展之动态创建对象和配置化开发(C++反射机制的实现)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a844651990/article/details/84392410

如果对简单工厂模式不够了解可以先看这里。简单工厂模式

流程

UML:
在这里插入图片描述

实现

首先定义一个函数指针

typedef void* (*Constructor)();

工厂类,用来注册、保存和创建要动态创建的类:

class CObjectFactory
{
public:
    static void registerClass(std::string className, Constructor constructor) {
        constructors()[className] = constructor;
    }

    static void *createObject(std::string className) {
       Constructor constructor = nullptr;
       if (constructors().find(className) != constructors().end())
               constructor = constructors().find(className)->second;

       if (constructor == nullptr)
               return nullptr;
       return (*constructor)();
    }

private:
    inline static std::map<std::string, Constructor> &constructors() {
        static std::map<std::string, Constructor> instance;
        return instance;
    }
};

注册宏:

#define REG_CLASS(className) \
class className##Helper   \
{   \
public: \
    className##Helper() { \
            CObjectFactory::registerClass(#className, className##Helper::createObjFunc); \
    } \
    static void* createObjFunc() { \
            return new ImpleTwo; \
    }\
}; \
className##Helper className##helper;

用户调用的工厂类:

class AutoFactory {
public:
    static Api* createApi() {
        Api* pApi = nullptr;
        pApi = static_cast<Api*>(CObjectFactory::createObject("ImpleTwo"));
        return pApi;
    }
};

使用方法:

class Api
{
public:
    virtual void test(string str) = 0;

protected:
    Api() {}
};

class ImpleOne : public Api
{
public:
    void test(string str) {
            cout << "this is Imple one: " << str << endl;
    }
};

class ImpleTwo : public Api
{
public:
    void test(string str) {
            cout << "this is Imple two: " << str << endl;
    }
};

REG_CLASS(ImpleTwo)
int main()
{
    Api* pApi = AutoFactory::createApi();
    pApi->test("test");

    system("pause");
    return 0;
}

优点

  减轻工厂的责任,添加产品时不必修改工厂的逻辑代码,即原有程序基本不用改变。动态地创建任意产品,完全解耦。可实现配置化开发,从配置文件中读取字符串动态创建对象,特别容易维护和扩展。

猜你喜欢

转载自blog.csdn.net/a844651990/article/details/84392410