装饰器实现单例模式
# 类装饰器 类实现单例模式
def singleton(cls):
_instance = {}
def _singleton(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs)
return _instance[cls]
return _singleton
@singleton
class A:
pass
if __name__ == '__main__':
a = A()
b = A()
print(a, b)