個人感覺使用比較方便
#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();