单例模式确保一个类只有一个实例,并提供全局访问点。

适用场景

  • 资源共享:配置类、日志类、线程池、数据库连接池
  • 控制全局资源访问

优缺点

优点缺点
全局访问难以扩展
控制实例数目隐藏依赖关系
节省资源并发问题

实现

class Singleton:
    _instance = None
 
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

线程安全

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

变体

  • 懒汉式:首次使用时创建
  • 饿汉式:类加载时创建