C++ 设计模式之单例模式
单例模式:类只有一个实例,并且全局可访问。
单例模式又分为饿汉模式和懒汉模式。
饿汉模式
饿汉模式是指类在加载时候就创建单例的对象。
// singleton.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
class Singleton {
public:
static Singleton* getInstance() {
return instance;
}
private:
static Singleton* instance;
};
#endif
// singleton.cpp
#include "singleton.h"
Singleton* Singleton::instance = new Singleton();
懒汉模式
懒汉模式是指在使用时候才创建单例的对象。获取实例的时候先判断实例是否为空,为空则创建实例并返回这个实例,否则返回已创建的实例。
// singleton.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
class Singleton {
public:
static Singleton* getInstance() {
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
private:
static Singleton* instance;
};
#endif
// singleton.cpp
#include "singleton.h"
Singleton* Singleton::instance = new Singleton();
加锁的饿汉模式
了解多线程安全的同学很容易看出上述代码的问题:如果多个线程同时进入 getInstance() 时候,实例都为空的话,则各自都会创建实例。很容易想到的一个方法就是加锁保证线程安全。
// singleton.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include <mutex>
class Singleton {
public:
static Singleton* getInstance() {
if (instance == nullptr) {
m_mutex.lock();
if (instance == nullptr) {
instance = new Singleton();
}
m_mutex.unlock();
}
return instance;
}
private:
static Singleton* instance;
static std::mutex m_mutex;
};
#endif
// singleton.cpp
#include "singleton.h"
Singleton* Singleton::instance = new Singleton();
std::mutex Singleton::m_mutex;
Meyers 单例模式
C++11 规定了 local static 在多线程条件下的初始化行为,要求编译器保证内部静态变量的线程安全性。
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include <iostream>
class Singleton {
private:
Singleton () {
std::cout << "Singleton ()" << std::endl;
}
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
};
#endif
可以测试如下:
#include "singleton.h"
#include <iostream>
#include <thread>
int main() {
for (int i = 0; i < 10; ++i) {
std::thread([]() {
std::cout << &Singleton::getInstance() << std::endl;
}).join();
}
std::cout << &Singleton::getInstance() << std::endl;
}
输出如下:
Singleton ()
0x5588c5412153
0x5588c5412153
0x5588c5412153
0x5588c5412153
0x5588c5412153
0x5588c5412153
0x5588c5412153
0x5588c5412153
0x5588c5412153
0x5588c5412153
0x5588c5412153
此外,拷贝构造函数和拷贝赋值操作可以使用 delete 标记来阻止编译器自动生成。
参考:
- 《大话设计模式》
- https://www.yuque.com/tomocat/txc11h/dq5xse