#include <iostream>
#include <string>
#include <map>
using namespace std;
typedef void* (*register_func)();
class CReflect
{
public:
static void* newInstance(const string& class_name)
{
std::map<string, register_func>::iterator it = m_register.find(class_name);
if (it == m_register.end())
{
return NULL;
}
else
{
return it->second();
}
}
static void registerClass(const string& class_name, register_func func)
{
m_register[class_name] = func;
}
private:
/* key is class name and value is function to create instance of class */
static std::map<string, register_func> m_register;
};
class Register
{
public:
Register(const string& class_name, register_func func)
{
CReflect::registerClass(class_name, func);
}
};
#define REGISTER_CLASS(class_name) \
class class_name##Register { \
public: \
static void* newInstance() { \
return new class_name; \
} \
private: \
static const Register reg; \
};\
const Register class_name##Register::reg(#class_name,class_name##Register::newInstance);
#pragma once
#include <iostream>
using namespace std;
class testA
{
public:
testA(void);
~testA(void);
public:
void Show(){ std::cout << "Hello reflect" << std::endl;}
};
#pragma once
#include "testA.h"
#include "Reflect.h"
class testB
{
public:
static testA * GetInstance(const std::string& strDevName)
{
if(strDevName.empty())
{
return NULL;
}
return (testA*)CReflect::newInstance(strDevName);
}
};
// reflect_test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "testA.h"
#include "testB.h"
int _tmain(int argc, _TCHAR* argv[])
{
testA *lp = testB::GetInstance("testA");
lp->Show();
return 0;
}
1.创建反射
2.创建工厂
3.创建需要创建的类
4.通过工厂获取相应的类指针