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

一、概念

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

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

二、饿汉式

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

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

运行结果为:

相关推荐
菜鸟一枚在这12 小时前
深入解析设计模式之单例模式
开发语言·javascript·单例模式
FLZJ_KL12 小时前
【设计模式】【创建型模式】单例模式(Singleton)
java·单例模式·设计模式
非 白14 小时前
【Java】单例模式
java·笔记·单例模式
攻城狮7号1 天前
【第三节】C++设计模式(创建型模式)-单例模式
c++·单例模式·设计模式
Niuguangshuo1 天前
Python 单例模式笔记
笔记·python·单例模式
coooliang2 天前
Flutter 中的单例模式
javascript·flutter·单例模式
鄃鳕2 天前
单例模式【C++设计模式】
c++·单例模式·设计模式
yuanpan3 天前
23种设计模式之《单例模式(Singleton)》在c#中的应用及理解
单例模式·设计模式·c#
小突突突4 天前
总结单例模式的写法(在线程安全的情况下)
java·开发语言·后端·单例模式·java-ee
老朋友此林4 天前
详解单例模式、模板方法及项目和源码应用
java·开发语言·单例模式