C++实现简单的反射——根据字符串创建类对象

2019-12-15  本文已影响0人  拉普拉斯妖kk
auto panel = (Object*)ObjectFactory::GetInstance()->CreateObject("Panel");
// 单例类模板
template<class T>
class Singleton
{
public:
    using object_type = T;
    struct object_creator
    {
        object_creator() { Singleton<T>::GetInstance(); }
    };

    static object_creator creator_object;
public:
    static object_type* GetInstance()
    {
        static object_type _instance;
        return &_instance;
    }
};
template<typename T> typename Singleton<T>::object_creator Singleton<T>::creator_object;
// 定义Object构造函数指针
using CreateObjectFunc = function<void*()>;

struct CreateObjectFuncClass {
    explicit CreateObjectFuncClass(CreateObjectFunc func) : create_func(func) {}
    CreateObjectFunc create_func;
};

// Object工厂类
class ObjectFactory : public Singleton<ObjectFactory> {
public:
    //返回void *减少了代码的耦合
    void* CreateObject(const string& class_name) {
        CreateObjectFunc createobj = nullptr;

        if (create_funcs_.find(class_name) != create_funcs_.end())
            createobj = create_funcs_.find(class_name)->second->create_func;

        if (createobj == nullptr)
            return nullptr;

        // 调用函数指针指向的函数 调用REGISTER_CLASS中宏的绑定函数,也就是运行new className代码
        return createobj();
    }

    void RegisterObject(const string& class_name, CreateObjectFunc func) {
        auto it = create_funcs_.find(class_name);
        if (it != create_funcs_.end())
            create_funcs_[class_name]->create_func = func;
        else
            create_funcs_.emplace(class_name, new CreateObjectFuncClass(func));
    }

    ~ObjectFactory() {
        for (auto it : create_funcs_)
        {
            if (it.second != nullptr)
            {
                delete it.second;
                it.second = nullptr;
            }
        }
        create_funcs_.clear();
    }

private:
    //缓存类名和生成类实例函数指针的map
    unordered_map<string, CreateObjectFuncClass* > create_funcs_;
};
#define REGISTERPANELCLASS(className) \
class className##PanelHelper { \
public: \
    className##PanelHelper() \
    { \
        ObjectFactory::GetInstance()->RegisterObject(#className, []() \
        { \
            auto* obj = new className(); \
            obj->SetClassName(#className); \
            return obj; \
        }); \
    } \
}; \
className##PanelHelper g_##className##_panelhelper;// 初始化一个helper的全局变量,执行构造函数中的RegisterObject执行。
// 所有类的基类
class Object
{
public:
    Object() {}
    virtual ~Object() {}

    void SetClassName(const string& name) { class_name_ = name; }
    string GetClassName() const { return class_name_; }

protected:
    string class_name_;
};

class Panel : public Object
{
public:
    Panel() {}
    ~Panel() {}
};
#include <iostream>
#include <unordered_map>
#include <functional>

using namespace std;

// 单例类模板
template<class T>
class Singleton
{
public:
    using object_type = T;
    struct object_creator
    {
        object_creator() { Singleton<T>::GetInstance(); }
    };

    static object_creator creator_object;
public:
    static object_type* GetInstance()
    {
        static object_type _instance;
        return &_instance;
    }
};
template<typename T> typename Singleton<T>::object_creator Singleton<T>::creator_object;


// 定义Object构造函数指针
using CreateObjectFunc = function<void*()>;

struct CreateObjectFuncClass {
    explicit CreateObjectFuncClass(CreateObjectFunc func) : create_func(func) {}
    CreateObjectFunc create_func;
};

// Object工厂类
class ObjectFactory : public Singleton<ObjectFactory> {
public:
    //返回void *减少了代码的耦合
    void* CreateObject(const string& class_name) {
        CreateObjectFunc createobj = nullptr;

        if (create_funcs_.find(class_name) != create_funcs_.end())
            createobj = create_funcs_.find(class_name)->second->create_func;

        if (createobj == nullptr)
            return nullptr;

        // 调用函数指针指向的函数 调用REGISTER_CLASS中宏的绑定函数,也就是运行new className代码
        return createobj();
    }

    void RegisterObject(const string& class_name, CreateObjectFunc func) {
        auto it = create_funcs_.find(class_name);
        if (it != create_funcs_.end())
            create_funcs_[class_name]->create_func = func;
        else
            create_funcs_.emplace(class_name, new CreateObjectFuncClass(func));
    }

    ~ObjectFactory() {
        for (auto it : create_funcs_)
        {
            if (it.second != nullptr)
            {
                delete it.second;
                it.second = nullptr;
            }
        }
        create_funcs_.clear();
    }

private:
    // 缓存类名和生成类实例函数指针的map
    unordered_map<string, CreateObjectFuncClass* > create_funcs_;
};


#define REGISTERPANELCLASS(className) \
class className##PanelHelper { \
public: \
    className##PanelHelper() \
    { \
        ObjectFactory::GetInstance()->RegisterObject(#className, []() \
        { \
            auto* obj = new className(); \
            obj->SetClassName(#className); \
            return obj; \
        }); \
    } \
}; \
className##PanelHelper g_##className##_panelhelper;// 初始化一个helper的全局变量,执行构造函数中的RegisterObject执行。


// 所有类的基类
class Object
{
public:
    Object() {}
    virtual ~Object() {}

    void SetClassName(const string& name) { class_name_ = name; }
    string GetClassName() const { return class_name_; }

protected:
    string class_name_;
};

class Panel : public Object
{
public:
    Panel() {}
    ~Panel() {}
};


int main() {
    REGISTERPANELCLASS(Panel)
    auto panel = (Object*)ObjectFactory::GetInstance()->CreateObject("Panel");
    auto name = panel->GetClassName();
    cout << name.c_str() << endl;
    delete panel;

    system("pause");

    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读