单例模式:一个类在内存中的对象就一个。
单例模式可以可节约系统内存空间,控制资源的使用。
单例模式写法分为懒汉式(线程不安全) 、饿汉式。
** 实现单例步骤**
- 构造函数私有化
- 增加静态私有的当前类的指针变量
- 提供静态对外接口,可以让用户获得单例对象
一:使用懒加载(快加载),只有在使用时才实例化
class Singleton_lazy{
public:
static Singleton_lazy* getIntance()
{
if(pobjetc==NULL)
{
pobject=new Singleton_lazy;
}
return pobject;
}
private:
Singleton_lazy(){};
static Singleton_lazy* pobject;
};
Singleton_lazy* Singleton_lazy::pobject=NULL;//类外初始化
二 :饿汉式构造
class Singleton_hungry {
public:
static Singleton_hungry* getIntance()
{
return pobject;
}
private:
Singleton_hungry(){};
static Singleton_hungry* pobject;
};
Singleton_hungry* Singleton_hungry::pobject=new Singleton_hungry;
懒汉式线程安全问题
考虑多线程安全问题,使用互斥锁
std::mutex g_mtx;
class Singleton_lazy{
public:
static Singleton_lazy* getIntance()
{
if(pobject===NULL)
{
std::lock_guard<mutex>locker(g_mtx);
pobject=new Singleton_lazy;
}
return pobject;
private:
Singleton_lazy(){};
static Singleton_lazy* pobject;
};
Singleton_lazy* Singleton_lazy::pobject=NULL;