刘收获

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

单例模式 C++

0x01  概念  

  单例模式最初的定义出现于《设计模式》(艾迪生维斯理):“保证一个类仅有一个实例,并提供一个访问它的全局访问点。”

  单例模式该的实现:构造函数声明为private或protect防止被外部函数实例化,内部保存一个private static的类指针保存唯一的实例,实例的构造是一个public的static静态类方法,该方法返回单例类唯一的实例。

 

 

0x02  实现方式

  

   1.懒汉模式(临界区实现线程安全)

   不到万不得已就不会去实例化类,也就是说在第一次用到类实例的时候才会去实例化,这是懒汉实现。

   由于要进行线程同步,所以在访问量比较大,或者可能访问的线程比较多时,采用饿汉实现,可以实现更好的性能。这是以空间换时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class singleton
{
protected:
  singleton()
  {
    InitializeCriticalSection(&CriticalSection);//初始化临界区
  }
   ~singleton()
  {
    DeleteCriticalSection(&CriticalSection);  //销毁临界区
  }
private:
  static singleton* p;
public:
  CRITICAL_SECTION CriticalSection; //临界区
  static singleton* initance();
};
  
pthread_mutex_t singleton::mutex;
singleton* singleton::p = NULL;
singleton* singleton::initance()
{
  if (p == NULL)
  {
    EnterCriticalSection(&CriticalSection);      //进入临界区
    if (p == NULL)
      p = new singleton();
    LeaveCriticalSection(&CriticalSection);
  }
  return p;
}

 内部静态变量的懒汉实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class singleton
{
protected:
  singleton()
  {
    pthread_mutex_init(&mutex);
  }
public:
  static pthread_mutex_t mutex;
  static singleton* initance();
  int a;
};
  
pthread_mutex_t singleton::mutex;
singleton* singleton::initance()
{
  pthread_mutex_lock(&mutex);
  static singleton obj;
  pthread_mutex_unlock(&mutex);
  return &obj;
}

  

 

 

 

 

   2.饿汉模式(本身满足多线程安全)

    饿汉饥不择食,在单例类定义的时候就进行实例化。

    在访问量较小时,采用懒汉实现。这是以时间换空间。

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class singleton
{
protected:
  singleton()
  {}
private:
  static singleton* p;
public:
  static singleton* initance();
};
singleton* singleton::p = new singleton;
singleton* singleton::initance()
{
  return p;
}

  

posted on   沉疴  阅读(175)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示