单例模式(Singleton Pattern)是一种创建型设计模式,确保一个类只有一个实例,并提供全局访问点。
class Singleton {
private:
static Singleton* instance;
Singleton() = default;
public:
static Singleton* getInstance() {
if (instance == nullptr) {
instance = new Singleton(); // 线程不安全!
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
问题分析:
class Singleton {
private:
static Singleton* instance;
static std::mutex mtx;
Singleton() = default;
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton* getInstance() {
std::lock_guard<std::mutex> lock(mtx); // 每次都加锁,性能差
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;
改进点:
class Singleton {
private:
Singleton() = default;
~Singleton() = default;
public:
// 禁止拷贝和赋值
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton& getInstance() {
static Singleton instance; // C++11起线程安全
return instance;
}
// 示例方法
void doSomething() {
std::cout << "Singleton working..." << std::endl;
}
};
优势分析:
template <typename T>
class Singleton {
public:
// 禁止拷贝和赋值
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static T& getInstance() {
static T instance;
return instance;
}
protected:
Singleton() = default;
~Singleton() = default;
};
// 使用示例
class Logger : public Singleton<Logger> {
friend class Singleton<Logger>; // 允许Singleton访问私有构造函数
private:
Logger() {
std::cout << "Logger initialized" << std::endl;
}
public:
void log(const std::string& message) {
std::cout << "[LOG] " << message << std::endl;
}
};
// 使用方法
int main() {
Logger::getInstance().log("Hello Singleton!");
return 0;
}
双重检查锁定(Double-Checked Locking Pattern)是一种优化技术,减少锁的使用频率:
if (!instance) { // 第一次检查(无锁)
std::lock_guard<std::mutex> lock(mtx);
if (!instance) { // 第二次检查(加锁后)
instance = new Singleton();
}
}
class UnsafeSingleton {
private:
static std::shared_ptr<UnsafeSingleton> instance;
static std::mutex mtx;
public:
static std::shared_ptr<UnsafeSingleton> getInstance() {
if (!instance) { // 问题:可能读到"半成品"对象
std::lock_guard<std::mutex> lock(mtx);
if (!instance) {
instance = std::make_shared<UnsafeSingleton>(); // 非原子操作
}
}
return instance;
}
};
问题根源: std::make_shared
的执行过程不是原子的:
其他线程可能在步骤2和3之间读到未完全构造的对象!
template <typename T>
class SafeDCLPSingleton {
private:
static std::atomic<std::shared_ptr<T>> instance;
static std::mutex mtx;
protected:
SafeDCLPSingleton() = default;
~SafeDCLPSingleton() = default;
public:
SafeDCLPSingleton(const SafeDCLPSingleton&) = delete;
SafeDCLPSingleton& operator=(const SafeDCLPSingleton&) = delete;
static std::shared_ptr<T> getInstance() {
// 原子读取
auto temp = instance.load(std::memory_order_acquire);
if (!temp) {
std::lock_guard<std::mutex> lock(mtx);
temp = instance.load(std::memory_order_relaxed);
if (!temp) {
temp = std::make_shared<T>();
// 原子写入
instance.store(temp, std::memory_order_release);
}
}
return temp;
}
};
// 静态成员定义
template <typename T>
std::atomic<std::shared_ptr<T>> SafeDCLPSingleton<T>::instance{nullptr};
template <typename T>
std::mutex SafeDCLPSingleton<T>::mtx;
class Logger : public Singleton<Logger> {
friend class Singleton<Logger>;
private:
std::mutex log_mtx;
std::ofstream log_file;
Logger() {
log_file.open("application.log", std::ios::app);
}
~Logger() {
if (log_file.is_open()) {
log_file.close();
}
}
public:
enum LogLevel { INFO, WARNING, ERROR };
void log(LogLevel level, const std::string& message) {
std::lock_guard<std::mutex> lock(log_mtx);
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
log_file << "[" << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S") << "] ";
switch (level) {
case INFO: log_file << "[INFO] "; break;
case WARNING: log_file << "[WARN] "; break;
case ERROR: log_file << "[ERROR] "; break;
}
log_file << message << std::endl;
log_file.flush();
}
};
// 使用示例
int main() {
Logger::getInstance().log(Logger::INFO, "Application started");
Logger::getInstance().log(Logger::ERROR, "Something went wrong");
return 0;
}
class ConfigManager : public Singleton<ConfigManager> {
friend class Singleton<ConfigManager>;
private:
std::unordered_map<std::string, std::string> config_data;
mutable std::shared_mutex config_mtx;
ConfigManager() {
loadFromFile("config.ini");
}
void loadFromFile(const std::string& filename) {
// 简化的配置文件加载逻辑
config_data["database_url"] = "localhost:3306";
config_data["max_connections"] = "100";
config_data["debug_mode"] = "true";
}
public:
std::string getValue(const std::string& key, const std::string& default_value = "") const {
std::shared_lock<std::shared_mutex> lock(config_mtx);
auto it = config_data.find(key);
return (it != config_data.end()) ? it->second : default_value;
}
void setValue(const std::string& key, const std::string& value) {
std::unique_lock<std::shared_mutex> lock(config_mtx);
config_data[key] = value;
}
int getIntValue(const std::string& key, int default_value = 0) const {
std::string str_value = getValue(key);
return str_value.empty() ? default_value : std::stoi(str_value);
}
bool getBoolValue(const std::string& key, bool default_value = false) const {
std::string str_value = getValue(key);
return str_value == "true" || str_value == "1";
}
};
template <typename T>
class NeverDestroySingleton {
public:
NeverDestroySingleton(const NeverDestroySingleton&) = delete;
NeverDestroySingleton& operator=(const NeverDestroySingleton&) = delete;
static T& getInstance() {
static T* instance = new T(); // 永远不会被析构
return *instance;
}
protected:
NeverDestroySingleton() = default;
~NeverDestroySingleton() = default;
};
使用场景:
注意: 这种方式会导致内存"泄漏",但在某些场景下是可接受的。
实现方式 | 线程安全 | 性能 | 内存管理 | 复杂度 | 推荐指数 |
---|---|---|---|---|---|
朴素实现 | ❌ | ⭐⭐⭐⭐⭐ | ❌ | ⭐ | ❌ |
加锁版本 | ✅ | ⭐⭐ | ❌ | ⭐⭐ | ❌ |
Meyers单例 | ✅ | ⭐⭐⭐⭐⭐ | ✅ | ⭐ | ⭐⭐⭐⭐⭐ |
单例模板 | ✅ | ⭐⭐⭐⭐⭐ | ✅ | ⭐⭐ | ⭐⭐⭐⭐⭐ |
安全DCLP | ✅ | ⭐⭐⭐⭐ | ✅ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
推荐:Meyers单例或单例模板
class MyClass : public Singleton<MyClass> {
friend class Singleton<MyClass>;
// 实现...
};
推荐:安全DCLP + atomic
// 文件:singleton.h
#pragma once
#include
#include
// 通用单例模板
template <typename T>
class Singleton {
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(Singleton&&) = delete;
static T& getInstance() {
static T instance;
return instance;
}
protected:
Singleton() = default;
virtual ~Singleton() = default;
};
// 使用宏简化定义(可选)
#define SINGLETON_CLASS(ClassName) \
friend class Singleton<ClassName>; \
private: \
ClassName(); \
~ClassName() = default;