class Singleton(object):
instance = None
lock_obj = threading.RLock()
def __new__(self, *args, **kwargs):
return self.get_instance( *args, **kwargs )
@classmethod
def get_instance(clazz, *args, **kwargs):
with clazz.lock_obj:
if clazz.instance is None:
clazz.instance = object.__new__(clazz, *args, **kwargs)
clazz.instance.init(*args, **kwargs)
return clazz.instance
def __init__(self, *args, **kwargs):
super( Singleton, self ).__init__(*args, **kwargs)
def init(self, *args, **kwargs):
pass
class Test(Singleton):
def init(self, *args, **kwargs):
#do initializations here, not in __init__
pass
print Test()
print Test()
The output of printing the value of the result of the "creating" the 2 Test objects will show that actually only one Test object was created.
This pattern is needed very often in Python, although when it is needed it addresses the problem very handily.
Note: this is code based off some searching earlier this year. I no longer remember exactly where I found the original that I based this work off of.
No comments:
Post a Comment