單例模式主要用于單一資源的訪問。
下面僅列出比較好的實(shí)現(xiàn)方式,該實(shí)現(xiàn)方式具有以下特征
- 支持多線程安全
- 正常銷毀
- 使用c++實(shí)現(xiàn):鎖的部分使用Qt的
QMutex
實(shí)現(xiàn)
Class Name:Singleton
Singleton.h
class Singleton
{
public:
static Singleton *GetInstance()
{
if(nullptr == singleton_)
{
singleton_creat_lock_.lock();
if(nullptr == singleton_)
{
static ConfigData singleton;
singleton_ = &singleton;
}
singleton_creat_lock_.unlock();
}
return singleton_;
}
private:
static QMutex singleton_creat_lock_;
static Singleton *singleton_;
Singleton(){};~Singleton(){};
Singleton.cpp
// 注意:一定要初始化成員變量,否則編譯時(shí)會(huì)出現(xiàn)undefined reference to的錯(cuò)誤
QMutex Singleton::singleton_creat_lock_;
Singleton *Singleton::singleton_ = nullptr;