保定聊城网站建设,wordpress弹窗视频,做网站优化两年遇到的SEO常态,青白江建设局网站文章目录 #xff08;三#xff09;创建型模式#xff1a;单例模式饿汉式懒汉式饿汉式 v.s. 懒汉式 #xff08;三#xff09;创建型模式#xff1a;单例模式
单例模式在于确保一个类只有一个实例#xff0c;并提供一个全局访问点来访问该实例。在某些情况下#xff0… 文章目录 三创建型模式单例模式饿汉式懒汉式饿汉式 v.s. 懒汉式 三创建型模式单例模式
单例模式在于确保一个类只有一个实例并提供一个全局访问点来访问该实例。在某些情况下某些代码组件如线程池日志记录器需要在整个应用程序中共享使用单例模式可以实现组件资源的复用并简化系统设计。
单例模式实现方式主要包括饿汉式和懒汉式两种。
饿汉式
饿汉式是指在类加载的时候就创建单例实例不管后续是否会使用这个实例。
class Singleton {
private:static Singleton* instance; // 静态成员变量属于类本身而不是类的任何特定对象Singleton() {} // 私有构造函数防止外部实例化public:static Singleton* getInstance() { // 全局访问点return instance;}
};Singleton* Singleton::instance new Singleton(); // 在静态成员变量初始化时创建实例示例
#include iostreamclass Singleton {
private:static Singleton* instance; Singleton() {} public:static Singleton* getInstance() {return instance;}void doSomething() {std::cout Doing something... std::endl;}};Singleton* Singleton::instance new Singleton();int main() {Singleton* s1 Singleton::getInstance();Singleton* s2 Singleton::getInstance();if (s1 s2) {std::cout s1 and s2 are the same instance std::endl;}s1-doSomething();return 0;
}s1 and s2 are the same instance
Doing something...在多线程环境下饿汉式是线程安全的因为实例在类加载时就已经创建好了不存在并发访问创建实例的问题。
懒汉式
懒汉式是指在第一次使用时才会创建单例实例实例的创建被延迟到第一次使用 getInstance() 方法时。
class Singleton {
private:static Singleton* instance;Singleton() {} public:static Singleton* getInstance() {if (instance nullptr) { // 第一次使用时才会创建单例实例instance new Singleton();}return instance;}
};Singleton* Singleton::instance nullptr;示例
#include iostream class Singleton {
private: static Singleton* instance; Singleton() {} // 私有构造函数 public: static Singleton* getInstance() { if (instance nullptr) { instance new Singleton(); } return instance; } void doSomething() { std::cout Doing something... std::endl; }
}; Singleton* Singleton::instance nullptr; // 静态成员变量初始化 int main() { Singleton* s1 Singleton::getInstance(); Singleton* s2 Singleton::getInstance(); if (s1 s2) { std::cout s1 and s2 are the same instance std::endl; } s1-doSomething(); return 0;
}
s1 and s2 are the same instance
Doing something...懒汉式在多线程环境下是不安全的因为多个线程可能同时进入判断条件导致创建多个实例。因此需要通过加锁等机制来保证线程安全: static std::mutex mtx;static Singleton* instance;Singleton* Singleton::getInstance() {// 使用互斥锁std::mutex来保证只有一个线程能够创建实例。std::lock_guardstd::mutex lock(mtx);if (instance nullptr) {instance new Singleton();}return instance;}为了避免每次调用都加锁产生额外的性能开销可以在加锁的基础上进行双重检查 static std::mutex mtx;static Singleton* instance;Singleton* Singleton::getInstance() {if (instance nullptr) {std::lock_guardstd::mutex lock(mtx);if (instance nullptr) {instance new Singleton();}}return instance;}饿汉式 v.s. 懒汉式
在饿汉式单例模式中单例的实例在程序启动时就立即创建。这种方式的好处在于它的简单性和线程安全性无需额外的同步机制。
在懒汉式单例模式中单例的实例是在首次被需要时才被创建。这种方式的好处在于它可以延迟实例的创建从而减少程序启动时的资源消耗和初始化时间。