Created
September 4, 2016 08:46
-
-
Save zhyq0826/69300a5b137d5669b71068872ea98d4c to your computer and use it in GitHub Desktop.
使用装饰器创建单例模式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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