#include <map>
#include <string>
#include <iostream>
using namespace std;
typedef void* (*createClass)(void) ;
class ClassFactory
{
public:
ClassFactory(){} ;
virtual ~ClassFactory(){} ;
void* getClassByName(string className) ;
void registClass(string name, createClass method) ;
static ClassFactory& sharedClassFactory() ;
private:
map<string, createClass> m_classMap ;
} ;
void* ClassFactory::getClassByName(string className)
{
map<string, createClass>::const_iterator iter ;
iter = m_classMap.find(className) ;
if ( iter == m_classMap.end() )
return NULL ;
else
return iter->second() ;
}
void ClassFactory::registClass(string name, createClass method)
{
m_classMap.insert(pair<string, createClass>(name, method)) ;
}
ClassFactory& ClassFactory::sharedClassFactory()
{
static ClassFactory _sharedClassFactory ;
return _sharedClassFactory ;
}
class DynamicClass
{
public:
DynamicClass(string name, createClass method)
{
ClassFactory::sharedClassFactory().registClass(name, method) ;
}
} ;
#define DECLARE_CLASS(className)\
string className##Name ; \
static DynamicClass* m_##className##dc ;
#define IMPLEMENT_CLASS(className) \
DynamicClass* className::m_##className##dc = \
new DynamicClass(#className, className::createInstance) ;
class BaseClass
{
private:
// DECLARE_CLASS(BaseClass)
public:
BaseClass() {}
virtual ~BaseClass() {}
virtual void display(){}
} ;
class HelloClass:public BaseClass{
public:
DECLARE_CLASS(HelloClass)
HelloClass() {}
virtual ~HelloClass(){}
static void* createInstance()
{
return new HelloClass() ;
}
virtual void display()
{
cout << "hello world" << endl ;
}
} ;
IMPLEMENT_CLASS(HelloClass)
int main()
{
BaseClass *pVar = (BaseClass*)ClassFactory::sharedClassFactory().getClassByName("HelloClass") ;
pVar->display() ;
}
c++实现简单反射
最新推荐文章于 2019-07-19 20:51:59 发布