单例模式(懒汉式,饿汉式,变体)

单例模式,用于确保一个类只有一个实例,并提供一个全局访问点以访问该实例。

饿汉式(Eager Initialization)

程序启动时就创建实例

#include <iostream>
class SingletonEager 
{
private:
    static SingletonEager* instance;
    SingletonEager() {} // 私有构造函数

public:
    static SingletonEager* getInstance() {
        return instance;
    }
};

SingletonEager* SingletonEager::instance = new SingletonEager; // 在程序启动时即创建实例

int main() 
{
    SingletonEager* instance1 = SingletonEager::getInstance();
    SingletonEager* instance2 = SingletonEager::getInstance();
    std::cout << (instance1 == instance2) << std::endl;  // 输出 1,两个指针变量的内容相同
    return 0;
}

懒汉式(Lazy Initialization)

延迟初始化,即在第一次访问时才创建实例。

缺点:不是线程安全的。因为它没有考虑多线程同时访问的情况。如果多个线程同时调用 getInstance() 方法,并且在 instance 还没有被初始化之前,它们可能会同时进入条件 if (!instance) 中,导致多次创建实例,这违反了单例模式的要求。

#include <iostream>

class SingletonLazy 
{
private:
    static SingletonLazy* instance;
    SingletonLazy() {} // 私有构造函数

public:
    static SingletonLazy* getInstance() 
    {
        if (!instance) {
            instance = new SingletonLazy;
        }
        return instance;
    }
};

SingletonLazy* SingletonLazy::instance = nullptr;

int main() {
    SingletonLazy* instance1 = SingletonLazy::getInstance();
    SingletonLazy* instance2 = SingletonLazy::getInstance();
    std::cout << (instance1 == instance2) << std::endl; // 输出 1,两个指针变量的内容相同
    return 0;
}

想要解决线程安全问题,需要做互斥操作,类似于下面这样,搞一个互斥锁

class SingletonLazyThreadSafe {
private:
    static SingletonLazyThreadSafe* instance;
    static std::mutex mutex;
    SingletonLazyThreadSafe() {} // 私有构造函数

public:
    static SingletonLazyThreadSafe* getInstance() {
        std::lock_guard<std::mutex> lock(mutex);
        if (!instance) {
            instance = new SingletonLazyThreadSafe;
        }
        return instance;
    }
};

变体

这种方式非常简洁,并且是线程安全的

#include <iostream>

class SingletonLazy 
{
private:
    SingletonLazy() {} // 私有构造函数

public:
    static SingletonLazy* getInstance() 
    {
    	static SingletonLazy* instance;

        return instance;
    }
};

SingletonLazy* SingletonLazy::instance = nullptr;

int main() 
{
    SingletonLazy* instance1 = SingletonLazy::getInstance();
    SingletonLazy* instance2 = SingletonLazy::getInstance();
    std::cout << (instance1 == instance2) << std::endl; // 输出 1,两个指针变量的内容相同
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宗浩多捞

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值