设计模式之单例模式(懒汉、饿汉)

本文详细解析了懒汉式与饿汉式单例模式的实现原理及代码示例,对比了两种模式下类实例化的时机,强调了线程安全在懒汉式实现中的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

饿汉式单例模式:单例模式定义的时候就开始初始化。

 

1.加锁的懒汉式(线程安全)

#include<mutex>

class Singleton{
private:
    //构造函数私有
    Singleton(){
       
    }
    ~Singleton(){}
    //阻止拷贝
    Singleton(const Singleton& rhs);
    Singleton& operator=(const Singleton&rhs);
    //指向实例的指针
       static Singleton *pInstance;
    //用于线程安全的锁
      static std::mutex Mutex;
public:
   //产生实例
    static Singleton* getInstance();
};
std::mutex Singleton::Mutex;
Singleton* Singleton::pInstance=nullptr;//初始化时,置为空

Singleton* Singleton::getInstance(){
    if(pInstance==nullptr){//注意,出错两次检查指针是否为空
          //加锁
          Mutex.lock();
          if(pInstance==nullptr)
              pInstance=new Singleton();
         //解锁
          Mutex.unlock();
    }
     
    return pInstance;
}

 

2.饿汉式

注意:单例的饿汉实现是线程安全的,因为对象在使用前就已经创建出来了。

class Singleton{
private:
    //构造函数私有
    Singleton(){
       
    }
    ~Singleton(){}
    //阻止拷贝
    Singleton(const Singleton& rhs);
    Singleton& operator=(const Singleton&rhs);
    //指向实例的指针
       static Singleton *pInstance;

public:
   //产生实例
    static Singleton* getInstance();
};

Singleton* Singleton::pInstance=new Singleton();//注意,在一开始时,就初始化指向示例的指针

Singleton* Singleton::getInstance(){
       //直接返回指向实例的指针
      return pInstance;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值