单例模式:无论如何实例化都是同一个实例
def singleton(cls):
"""单例模式的装饰器"""
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
with threading.Lock(): # 线程安全
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
如果是设备控制类,可通过sn等唯一标识区别实例
class Device:
_instances = {} # 用于存储实例
def __new__(cls, sn: str | None = None):
"""
控制实例的创建,防止重复实例化
"""
if sn is None:
sns = device_list()
if len(sns) == 1:
sn = sns[0]
elif len(sns) > 1:
raise Exception("存在多个设备,请指定设备序列号")
else:
raise Exception("未检测到设备")
if sn not in cls._instances: # 如果不存在该实例,则创建
instance = super().__new__(cls) # 调用父类 __new__ 方法
cls._instances[sn] = instance
return cls._instances[sn] # 返回已存在或新创建的实例
423

被折叠的 条评论
为什么被折叠?



