【单例模式(饿汉式和懒汉式)】

一、概念

单例模式就是一个类只能有一个实例,并且提供一个访问它的全局访问点。

通常通过私有化构造函数来实现只能通过类的内部创建实例。

二、饿汉式

饿汉式是单例模式中的一种,其特点为:在定义是就立即创建类的实例(真的饿了),但饿汉式是线程安全的,其核心代码如下:

cpp 复制代码
class Singleton{
private:
    Singleton(){}
    static Singleton* m_instance;
public:
    static Singleton* getInstance(){
        return m_instance;
    }
};
Singleton* Singleton::m_instance = new Singleton;

完整实例:

cpp 复制代码
#include <iostream>

using namespace std;

class Singleton {
    static Singleton* singleton;
    Singleton()
    {
        cout << "这是一个无参构造" << endl;
    }

    ~Singleton()
    {
        cout << "这是析构" << endl;
    }
public:
    static Singleton* getinstence()
    {
        return singleton;
    }

    void show_info()
    {
        cout << this << endl;
    }

    //将编译器自动提供的拷贝构造与等号运算符重载移除掉
    Singleton(const Singleton& other) = delete;
    void operator=(const Singleton& other) = delete;
};

Singleton* Singleton::singleton = new Singleton;

int main()
{
    Singleton* s1 = Singleton::getinstence();
    s1->show_info();
    Singleton* s2 = Singleton::getinstence();
    s2->show_info();
    Singleton* s3 = Singleton::getinstence();
    s3->show_info();

    return 0;
}

运行结果:

三、懒汉式

懒汉式也是单例模式的一种,其特点为:在需要用到的时候才会创建实例,具有懒加载的功能,其是线程不安全的,代码如下:

cpp 复制代码
class Singleton{
private:
    Singleton(){}
    static Singleton* m_instance;
public:
    static Singleton* getInstance(){
        if(m_instance == nullptr){
            m_instance = new Singleton;
        }
        return m_instance;
    }
};
Singleton* Singleton::m_instance = nullptr;

完整示例如下:

cpp 复制代码
#include <iostream>

using namespace std;

class Singleton {
    static Singleton* singleton;
    Singleton()
    {
        cout << "这是一个无参构造" << endl;
    }

    ~Singleton()
    {
        cout << "这是析构" << endl;
    }
public:
    static Singleton* getinstence()
    {
        if (singleton == nullptr) {
            singleton = new Singleton;
        }
        return singleton;
    }

    void show_info()
    {
        cout << this << endl;
    }

    //将编译器自动提供的拷贝构造与等号运算符重载移除掉
    Singleton(const Singleton& other) = delete;
    void operator=(const Singleton& other) = delete;
};

Singleton* Singleton::singleton = nullptr;

int main()
{
    Singleton* s1 = Singleton::getinstence();
    s1->show_info();
    Singleton* s2 = Singleton::getinstence();
    s2->show_info();
    Singleton* s3 = Singleton::getinstence();
    s3->show_info();

    return 0;
}

运行结果为:

相关推荐
Albert Edison1 天前
【项目设计】C++ 高并发内存池
数据结构·c++·单例模式·哈希算法·高并发
繁华似锦respect1 天前
HTTPS 中 TLS 协议详细过程 + 数字证书/签名深度解析
开发语言·c++·网络协议·http·单例模式·设计模式·https
yoyo君~3 天前
深入理解PX4飞控系统:多线程并发、原子操作与单例模式完全指南
学习·单例模式·机器人·无人机
繁华似锦respect4 天前
C++ 设计模式之单例模式详细介绍
服务器·开发语言·c++·windows·visualstudio·单例模式·设计模式
xunyan62344 天前
面向对象(下)-设计模式与单例设计模式
java·单例模式·设计模式
隔山打牛牛4 天前
单例模式:高效实现全局唯一实例
单例模式
stormsha4 天前
Java 设计模式探秘饿汉式与懒汉式单例模式的深度解析
java·单例模式·设计模式·java-ee
口袋物联4 天前
设计模式之单例模式在 C 语言中的应用(含 Linux 内核实例)
c语言·单例模式·设计模式
__万波__4 天前
二十三种设计模式(一)--单例模式
java·单例模式·设计模式
第二只羽毛5 天前
单例模式的初识
java·大数据·数据仓库·单例模式