Skip to content

Instantly share code, notes, and snippets.

@zhyq0826
Created September 4, 2016 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhyq0826/69300a5b137d5669b71068872ea98d4c to your computer and use it in GitHub Desktop.
Save zhyq0826/69300a5b137d5669b71068872ea98d4c to your computer and use it in GitHub Desktop.
使用装饰器创建单例模式
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