diff --git a/src/python/dm/common/utility/singleton.py b/src/python/dm/common/utility/singleton.py index 8325b6bcaa859dc8c2cca8778a26e3143def395f..00c0f215464f5e995bc5deaafd5f2405334d82ba 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