简介
- 保证一个class只有一个实体,并为它提供一个全局访问点。
- 种经过改进的全局变量。
懒汉模式
版本一
class Singleton
{
public :
static Singleton* instance()
{
if (!pInstance_)
pInstance = new Singleton();
return pInstance_;
}
private :
Singleton();
Singleton(const Singleton&);
~Singleton();
private:
static Singleton* pInstance_;
};
Singleton* Singleton::pInstance_ = nullptr;
版本二
class Singleton
{
public :
static Singleton* instance()
{
if (!pInstance_)
pInstance = new Singleton();
return pInstance_;
}
Singleton() = delete;
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
~Singleton() = delete;
private:
static Singleton* pInstance_;
};
Singleton* Singleton::pInstance_ = nullptr;
版本三
- 线程安全
class Singleton
{
public :
static Singleton* instance()
{
std::lock_gurad lg(mt);
if (!pInstance_)
pInstance = new Singleton();
return pInstance_;
}
Singleton() = delete;
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
~Singleton() = delete;
private:
static Singleton* pInstance_;
static std::mutex mt;
};
Singleton* Singleton::pInstance_ = nullptr;
std::mutex Singleton::mt;
- 双检测锁定
Singleton* Singleton::instance()
{
if (!pInstance_)
{
std::lock_gurad lg(mt);
if (!pInstance_)
pInstance = new Singleton();
}
return pInstance_;
}
版本四
class Singleton
{
public :
static Singleton& instance()
{
static Singleton inst;
return inst;
}
Singleton() = delete;
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
~Singleton() = delete;
private:
// ...
};
饿汉模式
class Singleton
{
public :
static Singleton& instance()
{
return inst;
}
Singleton() = delete;
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
~Singleton() = delete;
private:
static Singleton inst;
};
Singleton Singleton::inst;
避免资源泄露
Singleton构造函数可以(可能)索求广泛的资源:网络连接、OS互斥体和进程通讯(IPC)方法中的各种 handles、进程外的CORBA或 COM对象的reference,等等。
有效手段:第一次执行才初始化
Singleton& Singleton::instance()
{
static Singleton obj; // static变量,第一次执行才初始化
return obj ;
}
优先单例
class Singleton
{
public :
static Singleton& instance()
{
static Singleton inst;
return inst;
}
Singleton() = delete;
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
~Singleton() = delete;
private:
// ...
};
优点:
- 无线程安全问题
- 懒汉模式,只要被使用到时才创建对象
- 局部静态变量,能保证资源得到回收