Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
使用装饰器创建单例模式
def singleton(cls):
_instance = {}
def wrapper():
if cls not in _instance:
_instance[cls] = cls()
return _instance[cls]
return wrapper
@singleton
class A(object):
pass
@singleton
class B(object):
pass
if __name__ == '__main__':
a1 = A()
a2 = A()
assert id(a1) == id(a2)
b1 = B()
b2 = B()
assert id(b1) == id(b2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.