Singleton Pattern
使用函数装饰器实现单例
def singleton(cls):
_instance = {}
def inner():
if cls not in _instance:
_instance[cls] = cls()
return _instance[cls]
return inner
@singleton
class A(object):
def __init__(self):
pass
#test
cls1 = A()
cls2 = A()
print(id(cls1) == id(cls2))使用类装饰器实现单例
使用 __new__ 关键字实现单例
使用 metaclass 实现单例
Last updated