一、单例模式要点
1、构造函数设置为私有函数,不允许类外创建
2、提供静态接口供客户获取单例
3、将类指针设为静态,因为静态函数只能操作静态变量
4、静态类指针类外初始化
二、饿汉模式
- 实例创建时机:类被加载时
- 模式类别:线程安全
//饿汉模式
class singlehungry {
public:
static singlehungry* getInstance() {
return hungry;
}
private:
singlehungry() {};
static singlehungry* hungry;
};
singlehungry* singlehungry::hungry = new singlehungry();
三、懒汉模式
- 实例创建时机:第一次访问实例的时候创建
- 模式类别:线程不安全、线程安全1、线程安全2
//线程不安全之懒汉模式
class singlelazy {
public:
static singlelazy* getInstance() {
if (lazy == nullptr)
lazy = new singlelazy();
return lazy;
}
private:
singlelazy() {};
static singlelazy* lazy;
};
singlelazy* singlelazy::lazy = nullptr;
//线程安全之懒汉模式1——加锁
mutex mt;
class singlelazy {
public:
static singlelazy* getInstance() {
mt.lock();
if (lazy == nullptr)
lazy = new singlelazy();
mt.unlock();
return lazy;
}
private:
singlelazy(){};
static singlelazy* lazy;
};
singlelazy* singlelazy::lazy = nullptr;
//线程安全之懒汉模式2——双检索
mutex mt;
class singlelazy {
public:
static singlelazy* getInstance() {
if (lazy == nullptr) {
mt.lock();
if (lazy == nullptr)
lazy = new singlelazy();
mt.unlock();
}
return lazy;
}
private:
singlelazy(){};
static singlelazy* lazy;
};
singlelazy* singlelazy::lazy = nullptr;
四、单例模式的调用
int main()
{ //懒汉模式
singlelazy* lazy1 = singlelazy::getInstance();
singlelazy* lazy2 = singlelazy::getInstance();
if (lazy1 == lazy2)
cout << "singlelazy is single_example" << endl;
else
cout<< "singlelazy is not single_example" << endl;
//饿汉模式
singlehungry* hungry1 = singlehungry::getInstance();
singlehungry* hungry2 = singlehungry::getInstance();
if(hungry1==hungry2)
cout<< "singlehungry is single_example" << endl;
else
cout << "singlehungry is not single_example" << endl;
}