C++ 宏定义动态加载、工厂模式

来源:互联网 发布:linux临时设置环境变量 编辑:程序博客网 时间:2021/11/29 08:33
#include <string>
#include <map>
#include <iostream>




using namespace std;




typedef void* (*CreateClass)(void);




/*@类工厂,通过一个MAP成员来实现类名与类的实例化对象函数的映射
 * * @向外部提供一个接口函数,通过类名来创建该类对象
 * * @MAP是静态的,这样可以在程序运行前就可以存在
 * */
class ClassFactory
{
public:
static void* 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();
}
}




static void RegistClass(string name,CreateClass method)
{
m_classMap.insert(pair<string,CreateClass>(name,method));
}




private:
static map<string,CreateClass> m_classMap;
};




map<string,CreateClass> ClassFactory::m_classMap;




/*@动态创建类,动态创建的类通过包含该类的一个静态对象
 * *向类工厂里注册自己的创建对象函数
 * */
class GenDynamic
{
public:
GenDynamic(string name,CreateClass method)
{
ClassFactory::RegistClass(name,method);
}
};




/*@定义宏,类通过包含该宏,实现动态创建*/
#define DECLARE_RUNTIME(class_name)\
string class_name##Name;\
static GenDynamic* class_name##gd




/*@宏实现,类通过实现该宏,实现动态创建*/
#define IMPLEMENT_RUNTIME(class_name)\
 GenDynamic* class_name::class_name##gd\
= new GenDynamic(#class_name,class_name::CreateInstance);




/*@顶层父类*/
class AppServer
{
private:
DECLARE_RUNTIME(AppServer);
public:
AppServer()
{


}
static void* CreateInstance()
{
return new AppServer;
}
virtual void display()
{
cout<<"AppServer display()"<<endl;
}
};
IMPLEMENT_RUNTIME(AppServer)




class ChangeBackground:public AppServer
{
private:
DECLARE_RUNTIME(ChangeBackground);
public:
ChangeBackground()
{


}
static void* CreateInstance()
{
return new ChangeBackground;
}
virtual void display()
{
cout<<"ChangeBackground display()"<<endl;
}
};
IMPLEMENT_RUNTIME(ChangeBackground)


class login:public AppServer
{
private:
DECLARE_RUNTIME(login);
public:
login()
{


}
static void* CreateInstance()
{
return new login;
}
virtual void display()
{
cout<<"login display()"<<endl;
}
};
IMPLEMENT_RUNTIME(login)






int main()
{
string str = "login";
AppServer* p = (AppServer*)ClassFactory::GetClassByName(str);
p->display();

return 0;
}
0 0