Skip to content
Snippets Groups Projects
Forked from DM / dm-docs
261 commits behind, 839 commits ahead of the upstream repository.
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
singleton.py 2.09 KiB
#!/usr/bin/env python

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)
            instance.__init__(*args, **kwargs)
            cls.__instance = instance
        return cls.__instance

    @classmethod
    def getInstance(cls, *args, **kwargs):
        return cls.__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        # Only initialize once.
        if self.__class__.__instance is not None:
            return

####################################################################
# Testing
if __name__ == '__main__':
    print 'Testing Singleton class'
    s1 = Singleton.getInstance()
    s2 = Singleton()
    s3 = Singleton.getInstance()
    s4 = Singleton()
    print 'S1: ', s1
    print 'S2: ', s2
    print 'S3: ', s3
    print 'S4: ', s4
    class A(Singleton):
        __instance = None
        def __init__(self, x):
            if self.__class__.__instance is None:
                print 'in A.__init__()'
                self.x = x
    class B(Singleton):
        def __init__(self, x):
            self.x = x
    class C(Singleton):
        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 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
    print c2
    print c2.x, c1.x