一个类在整个程序中只有一个实例。配置对象、日志器、数据库连接池都适合用单例。
class Config:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
c1 = Config()
c2 = Config()
print(c1 is c2) # True
但上面的写法在多线程下可能创建多个实例。生产环境用模块级单例(Python 模块天然单例):
# config.py
class _Config:
db_url = "localhost"
config = _Config() # 模块加载时创建一次
# 其他地方
from config import config
print(config.db_url)
class Logger {
public:
static Logger& instance() {
static Logger inst; // C++11 起线程安全
return inst;
}
void log(const std::string& msg) { /* ... */ }
private:
Logger() = default;
~Logger() = default;
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
};
// 使用
Logger::instance().log("hello");
局部 static 变量在 C++11 后由编译器保证线程安全初始化,是 C++ 单例的最佳实践。
原则:单例好用但不要滥用。能用依赖注入就别用单例,测试时不好替换。