Skip to content

Instantly share code, notes, and snippets.

@ericzhong
Created May 24, 2017 00:41
Show Gist options
  • Save ericzhong/aa858ba8477320671cb052c8150ad9eb to your computer and use it in GitHub Desktop.
Save ericzhong/aa858ba8477320671cb052c8150ad9eb to your computer and use it in GitHub Desktop.
单例模式
# 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