c++单例模式

C++单例模式详解

1)C++入门级小知识,分享给将要学习或者正在学习C++开发的同学。

2)内容属于原创,若转载,请说明出处。

3)提供相关问题有偿答疑和支持。

单例模式也称为单件模式、单子模式,可能是使用最广泛的设计模式。其意图是保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享。有很多地方需要这样的功能模块,如系统的日志输出,GUI应用必须是单鼠标,MODEM的联接需要一条且只需要一条电话线,操作系统只能有一个窗口管理器,一台PC连一个键盘。
另外需要注意一个问题是:
在c++中不允许在类中定义自身类的对象,但是允许类中定义自身类的指针以及引用:

以上原因在于定义一个指针类型仅仅是占用4字节,在类中仅仅是占个位置,并且要是用指针a的话需要为其分配空间,在分配空间的时候会真正的实例化;
 

如下是单例模式的基础模型:
class CSingleton
{
private:
CSingleton() //构造函数是私有的
{
}
static CSingleton *m_pInstance;
public:
static CSingleton * GetInstance()
{
if(m_pInstance == NULL) //判断是否第一次调用
m_pInstance = new CSingleton();
return m_pInstance;
}
};


用户访问唯一实例的方法只有GetInstance()成员函数。如果不通过这个函数,任何创建实例的尝试都将失败,因为类的构造函数是私有的。
GetInstance()使用懒惰初始化,也就是说它的返回值是当这个函数首次被访问时被创建的。这是一种防弹设计——所有GetInstance()之后的调用都返回相同实例的指针;
如下:当释放的时候会出现double释放的异常,说明不管创建多少实例都只能拿到一个相同的实例:

懒汉模式:
实例1(拷贝构造创建对象)


实例2:(只能通过引用来访问对象实例)

有一种情况是,假如有两个人都各自拿到一个实例,一个人用完了调用delInstance接口将实例释放,那么另外一个人使用的时候就会出现异常,因此为了解决这个问题,我们引入一个计数器,当所有的人都不在使用的时候才去真正的去释放掉;如下:

对于这种单例的使用还要注意一个问题就多线程并发访问的问题:需要加锁

饿汉模式:(程序运行起来以后就创建了,不管用户使用或者是不使用,如下面的对象a就是一直存在)

### 单例模式的基本概念 单例模式是创建型设计模式的一种,其核心思想是确保一个类仅有一个实例,并提供一个全局访问点来获取这个实例。在程序运行期间,单例模式可以保证一个类只有一个实例对象,并提供全局访问接口[^1][^2][^4]。 ### 实现方法 #### 饿汉式 饿汉式在程序开始时就创建实例,线程安全,但可能会造成资源浪费。 ```cpp #include <iostream> class Singleton { public: static Singleton& getInstance() { return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton instance; }; Singleton Singleton::instance; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 懒汉式(非线程安全) 懒汉式在第一次使用时才创建实例,但非线程安全。 ```cpp #include <iostream> class Singleton { public: static Singleton* getInstance() { if (instance == nullptr) { instance = new Singleton(); } return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton* instance; }; Singleton* Singleton::instance = nullptr; int main() { Singleton* instance1 = Singleton::getInstance(); Singleton* instance2 = Singleton::getInstance(); instance1->showMessage(); if (instance1 == instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 懒汉式(线程安全) 使用互斥锁保证线程安全,但会有一定的性能开销。 ```cpp #include <iostream> #include <mutex> class Singleton { public: static Singleton& getInstance() { std::lock_guard<std::mutex> lock(mutex); if (instance == nullptr) { instance = new Singleton(); } return *instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton* instance; static std::mutex mutex; }; Singleton* Singleton::instance = nullptr; std::mutex Singleton::mutex; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` #### 基于局部静态变量(C++11及以上) 简洁、安全且高效,推荐使用。 ```cpp #include <iostream> class Singleton { public: static Singleton& getInstance() { static Singleton instance; return instance; } void showMessage() { std::cout << "Hello from Singleton!" << std::endl; } // 防止复制 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; private: Singleton() { std::cout << "Singleton Constructor Called" << std::endl; } }; int main() { Singleton& instance1 = Singleton::getInstance(); Singleton& instance2 = Singleton::getInstance(); instance1.showMessage(); if (&instance1 == &instance2) { std::cout << "Both instances are the same." << std::endl; } return 0; } ``` ### 使用场景 - **资源管理**:例如数据库连接池、文件系统操作等,避免多个实例同时操作同一资源导致冲突。 - **配置信息**:如全局的配置文件管理,确保所有模块使用相同的配置信息。 - **日志记录**:保证所有日志信息都记录到同一个日志文件中。 ### 注意事项 - **线程安全**:在多线程环境下,需要确保单例的创建和访问是线程安全的,可采用互斥锁或局部静态变量的方式。 - **生命周期管理**:确保单例对象在整个程序生命周期内的正确性,避免内存泄漏。 - **可测试性**:单例模式可能会影响代码的可测试性,可考虑使用依赖注入等技术来提高可测试性。 - **避免滥用**:单例模式会引入全局状态,过度使用可能导致代码耦合度增加,难以维护和扩展。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值