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

一、概念

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

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

二、饿汉式

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

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;
}

运行结果为:

相关推荐
源代码•宸5 天前
深入浅出设计模式——创建型模式之单例模式 Singleton
开发语言·c++·经验分享·单例模式·设计模式
Y第五个季节5 天前
设计模式:单例模式
单例模式
小钻风33666 天前
设计模式之单例模式及其在多线程下的使用
单例模式·设计模式
“αβ”8 天前
线程安全的单例模式
linux·服务器·开发语言·c++·单例模式·操作系统·vim
蝸牛ちゃん8 天前
设计模式(六)创建型:单例模式详解
单例模式·设计模式·系统架构·软考高级
oioihoii10 天前
C++实战案例:从static成员到线程安全的单例模式
java·c++·单例模式
归云鹤11 天前
设计模式十:单件模式 (Singleton Pattern)
单例模式·设计模式
YxVoyager14 天前
C++设计模式:单例模式 (现代C++主流实现方式Meyer‘s Singleton + 使用CRTP模板化)
c++·单例模式·设计模式
不愧是你呀15 天前
Muduo库中单例模式详解
开发语言·c++·单例模式
数字芯片实验室15 天前
单例模式的智慧:从UVM看控制的艺术
单例模式