Created
May 24, 2017 00:41
-
-
Save ericzhong/aa858ba8477320671cb052c8150ad9eb to your computer and use it in GitHub Desktop.
单例模式
This file contains hidden or 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
# Method-1 | |
class Foo(object): | |
__instance = None | |
def __new__(cls, *args, **kwargs): | |
if Foo.__instance is None: | |
Foo.__instance = object.__new__(cls, *args, **kwargs) | |
return Foo.__instance | |
a = Foo() | |
b = Foo() | |
print(a is b) | |
# Method-2 | |
def singleton(cls, *args, **kw): | |
instances = {} | |
def _singleton(): | |
if cls not in instances: | |
instances[cls] = cls(*args, **kw) | |
return instances[cls] | |
return _singleton | |
@singleton | |
class Woo(object): | |
pass | |
c = Woo() | |
d = Woo() | |
print(c is d) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment