懒汉模式:
class Singleton
{
private:
Singleton(){}
public:
static Singleton* getInstance();
private:
static Singleton * instance;
}
Singleton Singleton::instance = NULL;
Singleton* Singleton::getInstance()
{
if(instance == NULL)
{
lock();
if(instance == NULL)
{
instance = new Singleton();
}
unlock();
}
return instance;
}
局部静态变量的懒汉模式(因为没有new,所以不用考虑delete):
class Singleton
{
private:
Singleton(){}
public:
static Singleton* getInstance();
}
Singleton* Singleton::getInstance()
{
lock();
static Singleton instance;
unlock();
return &instance;
}
饿汉模式
class Singleton
{
private:
Singleton(){}
public:
static Singleton* getInstance();
private:
static Singleton * instance;
}
Singleton Singleton::instance = new Singleton();
Singleton* Singleton::getInstance()
{
return instance;
}
细节待仔细看
https://www.cnblogs.com/cxjchen/p/3148582.html 单例模式及C++实现代码
https://www.cnblogs.com/qiaoconglovelife/p/5851163.html C++单例模式与线程安全单例模式(懒汉/饿汉)
https://www.cnblogs.com/dupengcheng/p/7205527.html C++单例模式
http://www.cnblogs.com/chengkeke/p/5417371.html 单例模式