c++单例模式中的懒汉模式和饿汉模式
懒汉模式实现方式有两种
-
静态指针 + 用到时初始化
-
局部静态变量
为什么叫做懒汉模式,就是不到调用getInstance函数,这个类的对象是一直不存在的
懒汉模式的指针写法
#include <iostream>
using namespace std;
class A{
public:
void setUp(){
cout<<"inside setup"<<endl;
}
A(){
cout<<"constructor called!"<<endl;
}
static A* getInstance();
static A* aa;
};
A* A::aa = nullptr;
A* A::getInstance(){
if(aa == nullptr)
aa = new A;
return aa;
}
int main(){
A* aa1 = A::getInstance();
A* aa2 = A::getInstance();
if(aa1 == aa2)
cout << "Yes" <<endl;
else
cout << "No" <<endl;
cout << "Hello world!"<<endl;
return 0;
}
懒汉模式的局部变量
#include <iostream>
using namespace std;
class A{
public:
static A& getInstance();
void setup(){
cout<<"inside setup"<<endl;
}
private:
A(){
cout<<"constructor called!"<<endl;
}
};
A& A::getInstance(){
static A a;
return a;
}
int main()
{
A a1 = A::getInstance();
A a2 = A::getInstance();
cout<<"Hello world!"<<endl;
return 0;
}
饿汉模式实现方式有两种
-
饿了肯定要饥不择食。所以在单例类定义的时候就进行实例化。故没有多线程的问题。
-
直接定义静态对象
-
静态指针 + 类外初始化时new空间实现
局部静态变量写法
#include <iostream>
using namespace std;
class A{
public:
static A &getInstance(){
return aa;
}
void setup(){
cout<<"inside setup!"<<endl;
}
private:
A(){
cout<<"constructor called!"<<endl;
}
static A aa;
};
A A::aa;
int main(){
A aa1 = A::getInstance();
A aa2 = A::getInstance();
cout << "Hello world!"<<endl;
return 0;
}
静态指针写法
#include <iostream>
using namespace std;
class A{
public:
static A* getInstance(){
return aa;
}
void setup(){
cout<<"inside setup!"<<endl;
}
private:
static A* aa;
A(){
cout<<"constructor called!"<<endl;
}
};
A* A::aa = new A;
int main()
{
A* aa1 = A::getInstance();
A* aa2 = A::getInstance();
if(aa1 == aa2)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
cout << "Hello world!"<<endl;
return 0;
}
浙公网安备 33010602011771号