用宏实现的单例模式
个人感觉使用比较方便
#define SINGLETON_CLASS_NO_DEF_CONSTRUCT_BODY(class_name)\
private:\
class_name();\
class_name(const class_name&);\
class_name & operator = (const class_name &);\
public:\
static class_name & Instance()\
{\
static class_name one;\
return one;\
}
#define SINGLETON_CLASS(class_name)\
private:\
class_name(){}\
class_name(const class_name&);\
class_name & operator = (const class_name &);\
public:\
static class_name & Instance()\
{\
static class_name one;\
return one;\
}
两个宏的区别仅在于是否实现 默认的无参构造函数。使用例子:
// HostBasicInformation.h
class HostBasicInformation
{
SINGLETON_CLASS_NO_DEF_CONSTRUCT_BODY(HostBasicInformation)
public:
virtual ~HostBasicInformation();
std::string GetInstallCode();
};
// HostBasicInformation.cpp
// 若使用SINGLETON_CLASS ,则不需要自己定义无参构造函数
HostBasicInformation::HostBasicInformation(){
}
HostBasicInformation::~HostBasicInformation(){
}
std::string HostBasicInformation::GetInstallCode()
{
return "";
}
这种宏的方式,主要优点在于:能严格限制此类的使用方式,也就是只能当做单例来使用。
std::string str_installCode = HostBasicInformation::Instance().GetInstallCode();
补充:软件开发 , C语言 ,