单例模式

单例模式就是一个类只有一个实例。

为了保证一个类只有一个实例。为了保证一个类只有一个实例,要保证一开始这个类只有唯一一个实例,并且不能进行拷贝等赋值和移动操作。

因此有两种实现方式,第一个是懒汉实现,在需要的时候实例化,另一种是饿汉实现,一开始就实例化。

//懒汉实现
/*
**注意C++11以后加入了移动操作,也有了新语法=delete,
**但是为了格式整齐,统一让他们权限为private
*/
#ifndef __SINGLETON1__
#define __SINGLETON1__

class Singleton1 {
 public:
  static Singleton1* getInstance();
  ~Singleton1() {
    if(instance)
      delete instance;
  }
 private:
  Singleton1(){}
  Singleton1(const Singleton1 &&);
  Singleton1(const Singleton1 & );
  Singleton1& operator=(const Singleton1 &&);
  Singleton1& operator=(const Singleton1 & );
 private:
  static Singleton1 *instance;
};

Singleton1* Singleton1::instance = nullptr;

Singleton1* Singleton1::getInstance()
{
    if(instance == nullptr)
        instance = new Singleton1();
    return instance;
}

#endif //  __SINGLETON1__

/*---------------------------------------------*/
//饿汉实现 #ifndef __SINGELTON2__ #define __SINGELTON2__ class Singleton2 { public: static Singleton2* getInstance(); ~Singleton2() { if(instance) delete instance; } private: Singleton2() {} Singleton2(const Singleton2 &&); Singleton2(const Singleton2 & ); Singleton2& operator=(const Singleton2 &&); Singleton2& operator=(const Singleton2 & ); private: static Singleton2* instance; }; Singleton2* Singleton2::instance = new Singleton2(); Singleton2* Singleton2::getInstance(){ return instance; } #endif // !__SINGELTON2__

实例化时如下:

int main()
{
  Singleton1::getInstance();
Singleton2::getInstance();
return 0; }

以上懒汉代码只适合在单线程,懒汉实现在多线程是不安全的,因为有可能两个线程同时运行到实例化初,所以需要加锁,饿汉一直就是线程安全,因为一开始初始化只会保证有一个实例。多线程代码如下:

#ifndef __SINGLETOM_THREAD1__
#define __SINGLETOM_THREAD1__

#include <thread>
#include <mutex>
//加锁
class Singleton3 {
 public:
  static Singleton3* getInstance();
  ~Singleton3() {
    if(instance)
      delete instance;
  }

 private:
  Singleton3() {};
  Singleton3(const Singleton3 &&);
  Singleton3(const Singleton3 & );
  Singleton3 &operator=(const Singleton3 &&);
  Singleton3 &operator=(const Singleton3 & );

 private:
  static std::mutex mutex_s;
  static Singleton3* instance;
};

std::mutex Singleton3::mutex_s;
Singleton3* Singleton3::instance = nullptr;

Singleton3* Singleton3::getInstance()
{
  if (instance == nullptr) {
    mutex_s.lock();
    if (instance == nullptr)
      instance = new Singleton3();
      mutex_s.unlock();
  }
  return instance;
}

#endif // !__SINGLETOM_THREAD1__

 

转载于:https://www.cnblogs.com/CoderZSL/p/8536909.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值