单例模式:
1.保证类在内存中只能创建一个对象
单例模式分为:
1.饿汉模式:程序启动时就创建唯一对象
2.懒汉模式:用的时候才创建对象
相关经验:
- 饿汉模式(不会出现问题)
- 懒汉模式(可能会出现问题)
(1)延迟加载
(2)线程安全问题
(3)是多线程环境
(4)是有共享数据
(5)有多条语句操作共享数据
举例实现:
饿汉模式:
1.创建唯一对象首先要禁用构造函数,将构造函数声明为私有
2.定义静态成员变量,在类内有静态成员函数调用
3.为防止通过拷贝构造函数,赋值重载运算符创建对象,将他们也要声明称私有
*优点:*实现简单,安全
缺点:可能导致进程启动慢,如果有多个单例类对象实例启动,不确定顺序
class Singleton{
public:
static Singleton& getinstance()
{
return m_ins;
}
private:
Singleton()
{
}
Singleton(const Singleton&) = delete;
static Singleton m_ins;//静态成员变量须在类外定义
};
int main()
{
Singleton &s = Singleton::getinstance();
return 0;
}
懒汉模式:
在第一次使用类时创建对象
//懒汉模式 第一次使用时创建 延迟加载
#include<iostream>
#include<mutex>
#include<thread>
using namespace std;
class Slingleton{
public:
static volatile Slingleton* getinstrance()
{
if (m_pIns == nullptr)//防止线程阻塞
{
m_mutex.lock();
if (m_pIns == nullptr)//volatile Slingleton* Slingleton::m_pIns = nullptr;
//将定义的静态变量初始化为空,第一次使用时创建对象,后面在调用
//指针不为空就无法创建对象
{
m_pIns = new Slingleton;
}
m_mutex.unlock();
}
return m_pIns;
}
class Gc{
public:
~Gc()
{
if (m_pIns)
{
delete m_pIns;
m_pIns = nullptr;
}
}
};
private:
Slingleton()
{
}
Slingleton(const Slingleton &) = delete;
Slingleton &operator=(const Slingleton &) = delete;
static volatile Slingleton* m_pIns ;
static mutex m_mutex;
static Gc m_gc;//静态成员变量在程序结束时销毁,m_gc在程序结束时析构函数释放new开辟的空间
};
volatile Slingleton* Slingleton::m_pIns = nullptr;
mutex Slingleton::m_mutex;
Slingleton::Gc m_gc;
void Treadfunc()
{
cout << Slingleton::getinstrance() << endl;
}
void Test()
{thread t1(Treadfunc);
thread t2(Treadfunc);
thread t3(Treadfunc);
thread t4(Treadfunc);
thread t5(Treadfunc);
thread t6(Treadfunc);
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
t6.join();
}
int main()
{
Test();
system("pause");
return 0;
}