设计模式12——单例模式(Singleton)
·
单例:通过一个对象只能创建一个该类的实例。当然,可以创建两个指针指向该实例。
应用场景:比如在某个服务器程序中,该服务器的配置信息存放在一个文件中,这些配置数据由一个单例对象统一读取,然后服务进程中的其他对象再通过这个单例对象获取这些配置信息。这种方式简化了在复杂环境下的配置管理。其他还有如系统的日志输出、MODEM的联接需要一条且只需要一条电话线,操作系统只能有一个窗口管理器,一台PC连一个键盘等等。
当需要频繁调用该类时,单例类可以保证无需重复创建,节省资源。
1 懒汉模式
class Singleton{
private:
Singleton();
Singleton(const Singleton& other);
public:
static Singleton* getInstance();
static Singleton* m_instance;
};
首先所有单例类设计必须私有化构造函数、拷贝构造函数,
//线程非安全版本,两个线程检测同一个m_instance;
Singleton* Singleton::getInstance() {
if (m_instance == nullptr) {
m_instance = new Singleton();
}
return m_instance;
}
上述代码在单线程是安全的,它首先检测是否为空,但是在多线程中由于线程调度的问题,可鞥两个线程都检测到m_instance为空。
下面是调用锁的版本一共两个:
//线程安全版本,但锁的代价过高
Singleton* Singleton::getInstance() {
Lock lock;
if (m_instance == nullptr) {
m_instance = new Singleton();
}
return m_instance;
}
/双检查锁,但由于内存读写reorder不安全
Singleton* Singleton::getInstance() {
if(m_instance==nullptr){
Lock lock;
if (m_instance == nullptr) {
m_instance = new Singleton();
}
}
return m_instance;
}
在双检查锁中,reorder指的是new Singleton()时,编译器可能不是按我们所想的步骤进行的,他可能只分配了内存就返回了申请的地址,但还未调用构造函数,所以此时可能还是为空,另一线程在调用getInstance就会创建两个单例对象。
在C++11后的实现方式如下,解决了上述问题:
#include <iostream>
#include <mutex>
class Singleton {
private:
Singleton() {
std::cout << "Singleton constructed!\n";
}
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton* instance;
static std::once_flag onceFlag;
public:
static Singleton& getInstance() {
std::call_once(onceFlag, [] {
instance = new Singleton();
});
return *instance;
}
};
Singleton* Singleton::instance = nullptr;
std::once_flag Singleton::onceFlag;
还有一种方式,将单例对象以局部静态对象的方式定义在函数内部,
template<typename T>
class Singleton {
public:
static T& GetInstance() {
static T instance;
return instance;
}
Singleton(T&&) = delete;
Singleton(const T&) = delete;
void operator=(const T&) = delete;
protected:
Singleton() = default;
virtual ~Singleton() = default;
};
2 饿汉模式
饿汉模式采用静态对象+获取对象函数接口,避免了程序启动时构造函数的顺序不确定性,而有了函数获取后C++11可以保证多个线程不会同时进入静态变量的初始化流程。
class Singleton
{
public:
static Singleton* GetInstance();
private:
Singleton(){}
Singleton(const Singleton&);
private:
static Singleton* m_Instance;
};
//CPP文件
Singleton* Singleton::m_Instance=new Singleton();//类外定义-不要忘记写
Singleton* Singleton::GetInstance()
{
return m_Instance;
}
openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构
更多推荐


所有评论(0)