[C++]单例模式

引用:windows码农屠龙手册

github源码路径:https://github.com/dangwei-90/Design-Mode

单例模式

单例 Singleton 是设计模式的一种,其特点是只提供唯一一个类的实例,具有全局变量的特点,在任何位置都可以通过接口获取到那个唯一实例。

注:Demo包含C++11 static的demo加锁方式的demo

// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

// 参考大话设计模式 - 单例模式

// 只创建一个实例,常见于读取配置文件等。
// 暂不考虑释放问题。代码过于丑陋,较难维护,且意义不大。

#include <iostream>
#include <vector>
#include <mutex>

#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p){delete(p); (p)=NULL;} }
#endif

using namespace std;

// 通过 C++ 11 static 实现单例
class SingletonStatic {
public:
  ~SingletonStatic() {}

  static SingletonStatic* GetInstance() {
    static SingletonStatic* singleton_static = new SingletonStatic();
    return singleton_static;
  }
};

// 通过互斥锁方式实现单例
mutex g_mt_lock;

class Singleton {
public:
  ~Singleton() {
  }

  static Singleton* GetInstance() {
    if (singleton_ == nullptr) {
      g_mt_lock.lock();
      if (singleton_ == nullptr) {
        singleton_ = new Singleton();
      }
      g_mt_lock.unlock();
    }

    return singleton_;
  }

public:
  static Singleton* singleton_;
};
Singleton* Singleton::singleton_ = nullptr;


int main()
{
  // C++ 11 的 static 特性,实现单例模式
  SingletonStatic* test_a_static = SingletonStatic::GetInstance();
  SingletonStatic* test_b_static = SingletonStatic::GetInstance();
  if (test_a_static == test_b_static) {
    cout << "static same singleton" << endl;
  }
  else {
    cout << "static not same singleton" << endl;
  }

  // 加锁的方式实现单例模式
  Singleton* test_a = Singleton::GetInstance();
  Singleton* test_b = Singleton::GetInstance();
  if (test_a == test_b) {
    cout << "same singleton" << endl;
  }
  else {
    cout << "not same singleton" << endl;
  }

  /* 暂不考虑释放问题。代码过于丑陋,较难维护,且意义不大。
  //delete Singleton::GetInstance();
  delete test_a;
  test_a = nullptr;

  Singleton* test_c = Singleton::GetInstance();
  test_c->testfun();
  test_a->testfun();
  */

  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值