单例模式 Singleton

单例模式 Singleton

  • 饿汉模式

    class Singleton
    {
    public:
    	static Singleton* GetInstance()
        {
            return &instance_;
        }
    private:
        Singleton(){}
        Singleton(const Singleton&) = delete;
        Singleton& operator=(const Singleton&) = delete;
        
        static Singleton instance_;
    };
    
    • 特点
      1. 程序启动时就创建一个唯一的实例对象, 因为对象是静态的在数据段
      2. 如果单例类初始化功能太复杂,会导致进程启动慢
      3. 由于对象初始化顺序被编译器控制,用户不能确定启动顺序,对依赖单例加载不利
  • 懒汉模式

    class Singleton
    {
    public:
        static Singleton* GetInstance()
        {
            if(instance_ == nullptr) // 双重锁定,优化
            {
                std::lock_guard<std::mutex> guard(mut_);
                if(instance_ == nullptr)
                {
                    instance_ = new Singleton;
                    static GC gc; // 静态变量将会随着程序结束而被释放
                }
            }
            return instance_;
        }
        class GC
    	{
    	public:
    		~GC()
    		{
    			if (instance_)
    			{
    				delete instance_;
    				instance_ = nullptr;
    			}
    		}
    	};
    private:
        Singleton(){}
        Singleton(const Singleton&) = delete;
        Singleton& operator=(const Singleton&) = delete;
        
        static Singleton* instance_;
        static std::mutex mut_;
    };
    Singleton* Singleton::instance_ = nullptr;
    std::mutex Singleton::mut_ = nullptr;
    
    • 特定
      1. 解决进程启动慢,将构造函数中逻辑复杂或者其资源占用严重的对象在运行时实例化
      2. 多线程中不会产生竟态
      3. 双重锁定是优化避免每次都需要获取锁,单例模式只有在第一次实例化时才会发生竟态
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值