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

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

饿汉式(Eager Initialization)

程序启动时就创建实例

cpp 复制代码
#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) 中,导致多次创建实例,这违反了单例模式的要求。

c 复制代码
#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;
    }
};

变体

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

c 复制代码
#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;
}
相关推荐
为java加瓦1 天前
单例模式:原理、实现与演进
单例模式
磨十三1 天前
C++ 单例模式(Singleton)详解
c++·单例模式
默默coding的程序猿1 天前
1.单例模式有哪几种常见的实现方式?
java·开发语言·spring boot·spring·单例模式·设计模式·idea
程序员Aries5 天前
从零开始实现一个高并发内存池_DayThree:内存池整体框架与ThreadCache、TLS无锁访问
c++·学习·单例模式
爱奥尼欧5 天前
【Linux】系统部分——线程安全与线程的单例模式
linux·安全·单例模式
青草地溪水旁5 天前
第一章:单例模式 - 武林中的孤高剑客
单例模式
huangyuchi.6 天前
【Linux实战 】Linux 线程池的设计、实现与单例模式应用
linux·c++·单例模式·线程池·懒汉模式·项目·linux系统
拧之7 天前
✅设计模式笔记
笔记·单例模式·设计模式
蓝莓味的口香糖8 天前
【JS】什么是单例模式
开发语言·javascript·单例模式
稚辉君.MCA_P8_Java11 天前
DeepSeek Java 单例模式详解
java·spring boot·微服务·单例模式·kubernetes