文章目录
单例模式
单例模式,也叫单子模式,是一种常用的软件设计模式。 在应用这个模式时,单例对象的类必须保证只有一个实例存在。 许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。
懒汉式
不使用互斥(错误示范)
#include <iostream>
#include <thread>
using namespace std;
class Singelton
{
public:
static Singelton* GetInstance();
void FreeInstance();
private:
Singelton(); // 使构造函数私有
static Singelton* instance_;
};
Singelton* Singelton::instance_ = nullptr;
Singelton::Singelton()
{
cout << "构造函数:" << this << endl;
}
Singelton* Singelton::GetInstance()
{
// 没有锁,多线程下可能会多次实例化
if (instance_ == nullptr)
instance_ = new Singelton;
return instance_;
}
void Singelton::FreeInstance()
{
delete instance_;
instance_ = nullptr;
}
#pragma region 测试单例类
void thread_func(int id)
{
Singelton* instance = Singelton::GetInstance();
cout << "线程" << id << "获得实例:" << instance << endl;
}
int main()
{