单例属性可变
先看一个版本,这版本虽然能控制成一个单实例,但是实例的值却可以变。。
import threading
class Singleton: _instance = None _lock = threading.Lock() def __new__(cls, *args, **kwargs): # 加锁以确保线程安全 with cls._lock: if not cls._instance: cls._instance = super().__new__(cls) return cls._instance def __init__(self, value): self.value = value # 测试线程安全的单例模式
def create_singleton(value): return Singleton(value) # 创建两个看似独立的单例对象
singleton1 = create_singleton(1)
singleton2 = create_singleton(2) # 检查它们是否是同一个对象
print(singleton1 is singleton2) # 输出: True
print(singleton1.value) # 输出: 2
单例属性不可变
import threading class SingletonMeta(type): _instances = {} _lock = threading.Lock() def __call__(cls, *args, **kwargs): # 加锁以确保线程安全 with cls._lock: if cls not in cls._instances: cls._instances[cls] = super).__call__(*args, **kwargs) return cls._instances[cls] class Singleton(metaclass=SingletonMeta): def __init__(self, value): self.value = value def __str__(self): return f"Singleton({self.value})" # 测试线程安全的单例模式
def create_singleton(value): return Singleton(value) # 创建两个看似独立的单例对象
singleton1 = create_singleton(1)
singleton2 = create_singleton(2) # 检查它们是否是同一个对象
print(singleton1 is singleton2) # 输出: True
print(singleton1.value) # 输出: 1