Last active
May 4, 2016 08:36
-
-
Save gatspy/f8644f39e97641aaa5f45fc22de9cf1b to your computer and use it in GitHub Desktop.
python -- singleton
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
# Method 1: A decorator | |
def singleton(class_): | |
instances = {} | |
def getinstance(*args, **kwargs): | |
if class_ not in instances: | |
instances[class_] = class_(*args, **kwargs) | |
return instances[class_] | |
return getinstance | |
@singleton | |
class MySingleton(object): | |
pass | |
my1 = MySingleton() | |
my2 = MySingleton() | |
print id(my1) == id(my2) | |
print '----------------------' | |
# Method 2: metaclass | |
class Singleton(type): | |
_instances = {} | |
def __call__(cls, *args, **kwargs): | |
if cls not in cls._instances: | |
cls._instances[cls] = super( | |
Singleton, cls).__call__(*args, **kwargs) | |
return cls._instances[cls] | |
# Python2 | |
class MyClass(object): | |
__metaclass__ = Singleton | |
m1 = MyClass() | |
m2 = MyClass() | |
print id(m1) == id(m2) | |
print '----------------------' | |
def singleton(class_): | |
class class_w(class_): | |
_instance = None | |
def __new__(class_, *args, **kwargs): | |
if class_w._instance is None: | |
class_w._instance = super(class_w, | |
class_).__new__(class_, | |
*args, | |
**kwargs) | |
class_w._instance._sealed = False | |
return class_w._instance | |
def __init__(self, *args, **kwargs): | |
if self._sealed: | |
return | |
super(class_w, self).__init__(*args, **kwargs) | |
self._sealed = True | |
class_w.__name__ = class_.__name__ | |
return class_w | |
@singleton | |
class MyClass(object): | |
pass | |
print MyClass | |
print '---------------------' | |
import threading | |
class Singleton(object): | |
objs = {} | |
objs_locker = threading.Lock() | |
def __new__(cls, *args, **kwargs): | |
if cls in cls.objs: | |
return cls.objs[cls] | |
cls.objs_locker.acquire() | |
try: | |
if cls in cls.objs: | |
return cls.objs[cls] | |
cls.objs[cls] = super(Singleton, cls).__new__(cls) | |
finally: | |
cls.objs_locker.release() | |
return cls.objs[cls] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment