一、概念
保证一个类仅有一个实例,并提供一个该实例的全局访问点。—《设计模式》GoF
二、动机
在软件系统中,经常有这样一个特殊的类,必须保证它们在系统中只存在一个示例,才能确保他们的逻辑正确性、以及良好的效率。如何绕过常规的构造器,提供一种机制来保证一个类只有一个实例?工厂模式绕过new是为了避开紧耦合,单例模式避开new,是解决性能问题这个应该类设计者的责任,而不是使用者的责任。解决方案:
-
将构造函数设置为私有的;
-
提供一个全局的静态方法;
-
定义一个静态指针,指向本类的变量的静态变量指针。
三、单例模式的实现
class Singleton {
private:
Singleton();
Singleton(const Singleton& other);
public:
static Singleton* getInstance(); // 静态成员是类的成员而不是对象的成员
static Singleton* m_instance;
};
// 静态成员需要在类外初始化
Singleton* Singleton::m_instance = nullptr;
// 线程非安全版本
Singleton* Singleton::getInstance() { // 由于是在类的外部定义,也是静态方法,不用加static
if (m_instance == nullptr) {
// 下面这行代码可以被多个线程执行,因此不是线程安全的
m_instance = new Singleton();
}
return 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) {
// 分配内存->调用构造函数->赋值,但是编译器可能对这一过程进行优化,所以内存读写reorder不安全
m_instance = new Singleton();
}
}
return m_instance;
}
// C++ 11版本之后的跨平台实现 (volatile)
std::atomic<Singleton*> Singleton::m_instance; // 原子对象
std::mutex Singleton::m_mutex;
Singleton* Singleton::getInstance() {
Singleton* tmp = m_instance.load(std::memory_order_relaxed); // 屏蔽编译器reorder
std::atomic_thread_fence(std::memory_order_acquire); // 获取内存fence
if (tmp == nullptr) {
std::lock_guard<std::mutex> lock(m_mutex); // 锁的设置
tmp = m_instance.load(std::memory_order_relaxed); // 取变量出来
if (tmp == nullptr) {
tmp = new Singleton;
std::atomic_thread_fence(std::memory_order_release); // 释放内存fence
m_instance.store(tmp, std::memory_order_relaxed); // 存放变量回去
}
}
return tmp;
}
四、类图结构
五、要点总结
-
Singleton模式中的实例构造器可以设置为protected以允许子类派生。
-
Singleton模式一般不要支持拷贝构造函数和Clone接口,因为这有可能会导致多个对象实例,与Singleton模式的初衷相违背。
-
如何实现多线程环境下安全的Singleton?注意对双检查锁的正确实现。