zoukankan      html  css  js  c++  java
  • 017 --- 第21章 单例模式

    简述:

      单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

      单例模式包括:单例类。

      单例类:定义一个GetInstance操作,允许客户访问它的唯一实例,GetInstance是一个静态方法,主要负责创建自己的唯一实例。

    单例模式:仅提供一个线程安全双重锁定版本。

     1 #include <iostream>
     2 #include <mutex>
     3 using namespace std;
     4 
     5 class CSingleton
     6 {
     7 private:
     8     static CSingleton* m_pSingleton;
     9     static mutex m_Mutex;
    10 private:
    11     CSingleton() {};
    12 
    13 public:
    14     static CSingleton* GetInstance()
    15     {
    16         if (NULL == m_pSingleton)
    17         {
    18             lock_guard<mutex> myLock(m_Mutex);
    19             if (NULL == m_pSingleton)
    20             {
    21                 m_pSingleton = new CSingleton();
    22             }
    23         }
    24 
    25         return m_pSingleton;
    26     }
    27 };
    28 CSingleton* CSingleton::m_pSingleton = NULL;
    29 mutex CSingleton::m_Mutex;
    30 
    31 int main()
    32 {
    33     CSingleton* pSingleton1 = CSingleton::GetInstance();
    34     CSingleton* pSingleton2 = CSingleton::GetInstance();
    35 
    36     if (pSingleton1 == pSingleton2)
    37     {
    38         cout << "两个对象是相同的实例" << endl;
    39     }
    40 
    41     system("pause");
    42     return 0;
    43 }

    输出结果:

  • 相关阅读:
    msyql多个or,and,
    mysql中 where in 用法详解
    history.back(-1)和history.go(-1)的区别
    经典 mysql 28道题
    企业案例(二):增量恢复案例
    企业案例(一):由于mysql sleep线程过多小故障
    mysql数据库恢复
    binlog介绍
    mysql 数据库备份
    docker入门与实践
  • 原文地址:https://www.cnblogs.com/SmallAndGreat/p/13614454.html
Copyright © 2011-2022 走看看