当前位置: 首页> 科技> 名企 > 【单例模式(饿汉式和懒汉式)】

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

时间:2025/8/9 17:41:17来源:https://blog.csdn.net/Pumpkin_O/article/details/141251184 浏览次数:0次

一、概念

单例模式就是一个类只能有一个实例,并且提供一个访问它的全局访问点。
通常通过私有化构造函数来实现只能通过类的内部创建实例。

二、饿汉式

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

class Singleton{
private:Singleton(){}static Singleton* m_instance;
public:static Singleton* getInstance(){return m_instance;}
};
Singleton* Singleton::m_instance = new Singleton;

完整实例:

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

运行结果:
在这里插入图片描述

三、懒汉式

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

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;

完整示例如下:

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

运行结果为:
在这里插入图片描述

关键字:【单例模式(饿汉式和懒汉式)】

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: