DesignPatterns/c++/singleton.cc
2025-07-10 22:26:33 +08:00

25 lines
619 B
C++

/**
* @name 单例模式
* @brief: 确保类只有一个实例,并提供全局访问点
* @note 场景:日志记录器、配置管理、线程池、数据库连接池
*/
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance; // 线程安全 (C++11)
return instance;
}
void doSomething() { /* ... */ }
private:
Singleton() = default; // 私有构造
Singleton(const Singleton&) = delete; // 禁用拷贝
Singleton& operator=(const Singleton&) = delete;
};
// 使用
int main()
{
Singleton::getInstance().doSomething();
return 0;
}