架构能力的体现就是设计模式,设计模式共有23种。这篇文章介绍最常用的设计模式:单例模式。
单例模式
单例模式中全局只有一个实例,典型场景有日志类,数据封装类。在单例模式类的设计中,
私有成员:
- 构造函数
- 析构函数
- 拷贝构造函数
- 赋值运算符重载
- 静态成员变量(保存唯一的类指针)
公有成员:
- 用于表示类的成员的静态成员函数
单例模式又可以分为懒汉单例和饿汉单例。
懒汉单例:只有需要使用类的实例时才去创建类的实例
饿汉单例:系统一运行就已经创建好了实例
单例模式的简单实现:
#include <iostream>
#include <mutex>
using namespace std;
mutex g_mutex;
class Singleton
{
private:
Singleton() {}
~Singleton(){}
Singleton(const Singleton &t){}
void operator=(const Singleton &t){}
static Singleton* volatile sm_obj; // volatile 防止被优化
public:
static Singleton* getInstance()
{
if (sm_obj == nullptr) {
lock_guard<mutex> lg(g_mutex); // 守卫锁
//g_mutex.lock();
if (sm_obj == nullptr) { //双重校验防止多线程有多个实例(懒汉单例)
sm_obj = new Singleton;
}
//g_mutex.unlock();
}
return sm_obj;
}
void release()
{
if (sm_obj) {
delete sm_obj;
sm_obj = nullptr;
}
}
};
Singleton * volatile Singleton::sm_obj = nullptr; // 懒汉单例:以时间换空间
//Singleton *Singleton::sm_obj = new Singleton; // 饿汉单例:以空间换时间