//---------------------------------------------------------------------------
#pragma hdrstop
#include "untFactory.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//定义一个函数指针TCreateMe
typedef TComponent* (*TCreateMe)(TComponent* Owner);
//保存类信息的结构
struct TMyClassInfo
{
AnsiString ClassName;
TCreateMe CreateMe;
TMyClassInfo(AnsiString const &aClassName,TCreateMe aCreateMe):
ClassName(aClassName),CreateMe(aCreateMe){}
};
//重载==
bool operator ==(TMyClassInfo const &A,AnsiString const &ClassName)
{
return A.ClassName==ClassName;
}
//工厂类
class TMyClassFactory
{
static std::vector<TMyClassInfo> ClassInfo;
public:
//注册类函数
static inline void RegisterClass(AnsiString const &ClassName,
TCreateMe CreateMe)
{
ClassInfo.push_back(TMyClassInfo(ClassName,CreateMe));
}
//生成类函数
static TComponent* CreateObject(AnsiString const &ClassName,TComponent * Owner)
{
std::vector<TMyClassInfo>::iterator pos;
pos=std::find(ClassInfo.begin(),ClassInfo.end(),ClassName);
if(pos!=ClassInfo.end())
return pos->CreateMe(Owner);
return NULL;
}
static inline void DeleteObject(TComponent* x){delete x;}
};
std::vector<TMyClassInfo> TMyClassFactory::ClassInfo; //初始化vector
//创建一个类的模板函数
template <typename T>
TComponent* _Class_CreateMe(TComponent* Owner){return new T(Owner);}
//new一个对象的模板函数
template <typename T>
inline T* FactoryCreateObject(AnsiString const &ClassName,TComponent* Owner=NULL)
{
return (T*)TMyClassFactory::CreateObject(ClassName,Owner);
}
#define FactoryRegisterClass(T) TMyClassFactory::RegisterClass(#T,_Class_CreateMe<T>);
使用方法:
1,注册:FactoryRegister(TForm1);
2,从类名生成实例
TForm *pForm=FactoryCreateobject<TForm>("TForm1",this);
或
TForm* pForm=(TForm*)TMyClassFactory::CreateObject("TForm1",this);
其实 现在各种类库的rtti基本都已非常完善,只要根据其提供的api即可,这里仅是研究下C++中的模板等用法而已。