C++ 中泛型工厂注册类的实现

王朝c/c++·作者佚名  2006-01-09
宽屏版  字体: |||超大  

//C++ 中泛型工厂注册类的实现

//---------------------------------------------------------------------------

#ifndef GenericFactoryH

#define GenericFactoryH

#include <string>

#include <map>

#define REGISTER_CLASS(BASE_CLASS, DERIVED_CLASS) RegisterInpFactory<BASE_CLASS, DERIVED_CLASS> Register##DERIVED_CLASS(#DERIVED_CLASS)

#define CREATE_CLASS(BASE_CLASS,DERIVED_CLASS) GenericFactory<BASE_CLASS>::instance().Create(#DERIVED_CLASS)

//---------------------------------------------------------------------------

using std::string;

using std::map;

template <class ManufacturedType, typename ClassIDKey=std::string>

class GenericFactory

{

typedef ManufacturedType* (*BaseCreateFn)();

typedef std::map<ClassIDKey, BaseCreateFn> FnRegistry;

FnRegistry registry;

GenericFactory() {}

GenericFactory(const GenericFactory&) {} // 没有实现

GenericFactory &operator=(const GenericFactory&) {} // 没有实现

public:

static GenericFactory& instance()

{

static GenericFactory<ManufacturedType,ClassIDKey> bf;

return bf;

}

void RegCreateFn(const ClassIDKey &classname, BaseCreateFn fn)

{

registry[classname] = fn;

}

ManufacturedType* Create(const ClassIDKey &classname) const

{

ManufacturedType* theObject(0);

FnRegistry::const_iterator regEntry = registry.find(classname);

if (regEntry != registry.end())

{

theObject = regEntry->second();

}

return theObject;

}

};

template <class AncestorType, class ManufacturedType, typename ClassIDKey=std::string>

class RegisterInpFactory

{

public:

static AncestorType* CreateInstance()

{

return (new ManufacturedType);

}

RegisterInpFactory(const ClassIDKey &id)

{

GenericFactory<AncestorType,ClassIDKey>::instance().RegCreateFn(id, CreateInstance);

}

};

#endif

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有