装饰器实现单例模式

# 类装饰器 类实现单例模式
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)
posted @ 2022-05-23 17:52  wyz_1  阅读(15)  评论(0编辑  收藏  举报