https://blog.csdn.net/weixin_43754049/article/details/125888390
#include <iostream>
using namespace std;
//单例 分为懒汉式 和 饿汉式
class Singleton_lazy {
private:
Singleton_lazy() {cout << "Singleton_lazy()" << endl;}
public:
//增加一个条件判断 如果静态变量为空 则创建一个对象返回
static Singleton_lazy* getInstance() {
cout << "Singleton_lazy-----getInstance()" << endl;
if (pSingleton == NULL) {
pSingleton = new Singleton_lazy;
}
return pSingleton;
}
//这个释放堆区对象的方式不能提供 太危险了
//只要有一个人释放 大家共享的对象就都没了
/*static void freeSpace() {
if (pSingleton != NULL) {
delete pSingleton;
pSingleton = NULL;
}
}*/
private:
static Singleton_lazy* pSingleton;
};
//类外初始化
Singleton_lazy* Singleton_lazy::pSingleton = NULL;
class Singleton_hungry { //饿汉式
private:
Singleton_hungry() { cout << "我是饿汉式构造" << endl; }
public:
//可以发现这里没有条件判断了
static Singleton_hungry* getInstance() {
cout << "Singleton_hungry-----getInstance()" << endl;
return pSingleton;
}
private:
static Singleton_hungry* pSingleton;
};
//类外初始化 初始化的时候直接创建对象
Singleton_hungry* Singleton_hungry::pSingleton = new Singleton_hungry;
void test01() {
cout << "in test01()" << endl;
Singleton_lazy* p1 = Singleton_lazy::getInstance();
Singleton_lazy* p2 = Singleton_lazy::getInstance();
if (p1 == p2) {
cout << "两个指针指向同一块内存 是单例" << endl;
}
else {
cout << "不是单例模式" << endl;
}
}
void test02() {
cout << "in test02()" << endl;
Singleton_hungry* p1 = Singleton_hungry::getInstance();
Singleton_hungry* p2 = Singleton_hungry::getInstance();
if (p1 == p2) {
cout << "两个指针指向同一块内存 是单例" << endl;
}
else {
cout << "不是单例模式" << endl;
}
}
int main() {
cout << "我是main函数" << endl;
test01();
test02();
return 0;
}