单例模式确保一个类只有一个实例,并提供全局访问点。
适用场景
- 资源共享:配置类、日志类、线程池、数据库连接池
- 控制全局资源访问
优缺点
| 优点 | 缺点 |
|---|
| 全局访问 | 难以扩展 |
| 控制实例数目 | 隐藏依赖关系 |
| 节省资源 | 并发问题 |
实现
1
2
3
4
5
6
7
| class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
|
线程安全
1
2
3
4
5
6
7
8
9
10
11
| import threading
class Singleton:
_instance = None
_lock = threading.Lock()
def __new__(cls):
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
|
变体
Comments