参考书籍:《C++ 设计模式》李阳阳
cpp
#pragma once
#inlcude <iostream>
using namespace std;
#include <mutex>
struct lugard_sync {
explicit lugard_sync(std::mutex &_mutex) : m_mutex(_mutex) {
m_mutex.lock();
}
~lugard_sync() { m_mutex.unlock(); }
private:
std::mutex &m_mutex;
}
class Monitor {
private:
// 注意点 1:单例类的构造函数是私有的,这样能够保证
// 外部类无法调用该构造函数来生成多个实例
Monitor() {}
// 注意点 2:为避免类在外部实例化,该类自身必须定义
// 一个静态私有实例
static Monitor *instance;
public:
// 注意点 3:向外提供一个静态的公有函数,用于创建或
// 获取该静态私有实例
static Monitor* get_instance() {
std::mutex mt;
lugard_sync(mt);
if (instance == nullptr) {
instance = new Monitor();
}
return instance;
}