Python 使用装饰器实现单例模式
def singleton(cls): instances = {} def getinstance(*args,**kwargs): if cls not in instances: instances[cls] = cls(*args,**kwargs) return instances[cls] return getinstance @singleton class MyClass: a = 1 c1 = MyClass() c2 = MyClass() print(c1 == c2) # True
定义一个@singleton装饰器,内部函数getinstance会判断类是否在字典中