什么是单例模式

单例模式:

1.保证类在内存中只能创建一个对象

单例模式分为:

1.饿汉模式:程序启动时就创建唯一对象
2.懒汉模式:用的时候才创建对象

相关经验:

  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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值