单例模式分为两种
- 懒汉模式:第一次调用时才初始化,有延迟加载的效果,以时间换空间
优点:第一次使用实例对象时,创建对象。进程启动无负载。多个单例实例启动顺序自由控制。
缺点:复杂
- 饿汉模式:程序开始就初始化,以空间换时间
优点:简单
缺点:可能会导致进程启动慢,且如果有多个单例类对象实例启动顺序不确定。
懒汉模式一:双检索+自动回收
class Singleton {
public:
Singleton * GetInsTance()
{
if (m_PInstance == nullptr)
{
m_tex.lock();
if (m_PInstance == nullptr)
m_PInstance = new Singleton();
m_tex.unlock();
}
return m_PInstance;
}
//实现一个内嵌垃圾回收类
class CGarbo {
~CGarbo()
{
if (m_PInstance != nullptr)
{
delete Singleton::m_PInstance;
Singleton::m_PInstance = nullptr;
}
}
};
//定义一个静态变量,程序结束时,系统会自动调用它的析构函数,从而释放单例
static CGarbo cgarbo;
private:
//构造函数私有,防拷贝