单例模式c++实现

单例模式是一种创建型设计模式,它保证一个类仅有一个实例,并提供一个全局访问点来访问这个唯一实例。下面是一个简单的C++实现单例模式的例子:

cpp

#include <iostream>
#include <mutex>
class Singleton {
private:
static Singleton* instance;
static std::mutex mtx;
Singleton() {} // 私有构造函数,防止外部创建实例
Singleton(const Singleton&) = delete; // 删除拷贝构造函数
Singleton& operator=(const Singleton&) = delete; // 删除赋值操作符
public:
static Singleton* getInstance() {
std::lock_guard<std::mutex> lock(mtx); // 使用互斥锁保证线程安全
if (!instance) {
instance = new Singleton();
}
return instance;
}
void doSomething() {
std::cout << "Singleton instance is doing something." << std::endl;
}
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;
int main() {
Singleton* s1 = Singleton::getInstance();
Singleton* s2 = Singleton::getInstance();
if (s1 == s2) {
std::cout << "s1 and s2 are the same instance." << std::endl;
} else {
std::cout << "s1 and s2 are not the same instance." << std::endl;
}
s1->doSomething();
s2->doSomething();
delete s1; // 注意:通常我们不会显式删除单例对象,除非你确定应用程序即将结束
return 0;
}

在这个例子中,我们使用了互斥锁(std::mutex)来保证在多线程环境下getInstance方法的线程安全性。当getInstance方法被首次调用时,它会创建一个新的Singleton实例并将其赋值给静态成员变量instance。在后续的调用中,getInstance方法会返回已经存在的实例。

注意,单例模式通常用于那些只需要一个实例的类,例如配置管理类、日志记录类等。然而,过度使用单例模式可能会导致代码难以理解和维护,因此在使用时应谨慎考虑。

posted @   东岸  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示