From 2952ab6dee669e198bb3e535788a3f05b0de98a7 Mon Sep 17 00:00:00 2001 From: Sinisa Veseli <sveseli@aps.anl.gov> Date: Tue, 14 Apr 2015 13:19:20 +0000 Subject: [PATCH] reordered initialization call, added some test code --- src/python/dm/common/utility/singleton.py | 29 +++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/python/dm/common/utility/singleton.py b/src/python/dm/common/utility/singleton.py index 8325b6bc..00c0f215 100755 --- a/src/python/dm/common/utility/singleton.py +++ b/src/python/dm/common/utility/singleton.py @@ -4,12 +4,16 @@ class Singleton(object): __instance = None + # This class will behave properly as long as getInstance() is called. + # If object is constructed using constructor, __init__() will be called + # multiple times in the derived class (i.e., one needs protection + # against multiple initializations in the derived class) def __new__(cls, *args, **kwargs): # Allow subclasses to create their own instances. if cls.__instance is None or cls != type(cls.__instance): instance = object.__new__(cls, *args, **kwargs) - cls.__instance = instance instance.__init__(*args, **kwargs) + cls.__instance = instance return cls.__instance @classmethod @@ -18,12 +22,13 @@ class Singleton(object): def __init__(self, *args, **kwargs): # Only initialize once. - if Singleton.__instance is not None: + if self.__class__.__instance is not None: return #################################################################### # Testing if __name__ == '__main__': + print 'Testing Singleton class' s1 = Singleton.getInstance() s2 = Singleton() s3 = Singleton.getInstance() @@ -33,8 +38,11 @@ if __name__ == '__main__': print 'S3: ', s3 print 'S4: ', s4 class A(Singleton): + __instance = None def __init__(self, x): - self.x = x + if self.__class__.__instance is None: + print 'in A.__init__()' + self.x = x class B(Singleton): def __init__(self, x): self.x = x @@ -42,18 +50,31 @@ if __name__ == '__main__': def __init__(self): self.x = 14 + print + print 'Testing Class A' + print 'Init A(3)' a1 = A(3) + print 'Init A(4)' a2 = A(4) + print 'A.getInstance()' + a3 = A.getInstance() + print 'A.getInstance()' + a4 = A.getInstance() print a1 print a2 - print a2.x, a1.x + print a3 + print a3.x, a2.x, a1.x + print + print 'Testing Class B' b1 = B(6) b2 = B(5) print b1 print b2 print b2.x, b1.x + print + print 'Testing Class C' c1 = C() c2 = C() print c1 -- GitLab