单例模式的装饰器实现

def singleton(cls):
__instance = {}

def wrapper(x):
if cls in __instance:
return __instance[cls]
else:
__instance[cls] = cls(x)
return __instance[cls]
return wrapper


# @singleton
class A:
def __init__(self,x=0):
self.x = x

a1 = A(1)
a2 = A(2)
print(a1)
print(a2)

posted on 2019-08-08 16:02  lbky  阅读(592)  评论(0编辑  收藏  举报

导航