一、饿汉模式
特点:一开始就创建,线程安全。
缺点:过早创建实例,降低内存使用效率。
class Singleton {
private:
Singleton(){};
static Singleton* sInstance;
public:
static Singleton* getInstance() {
return sInstance;
}
static void Destory() {
delete sInstance;
sInstance = NULL;
}
};
Singleton* Singleton::sInstance = new Singleton();
二、懒汉模式
需要的时候再创建实例,多线程加锁
class Singleton {
private:
Singleton(){};
static Singleton* sInstance;
static std::mutex m_mutext;
public:
static Singleton* getInstance() {
if(sInstance == NULL) {
m_mutext.lock();
if(sInstance == NULL) {
sInstance = new Singleton();
}
m_mutext.unlock();
}
return sInstance;
}
static void Destory() {
delete sInstance;
sInstance = NULL;
}
};