Singleton Design Pattern

Singleton design pattern is well known design pattern which uses a single object to access its methods at all time. Assume that you have a configuration file to read settings from. You are expecting to access various settings from different source files. With singleton you’ll hold a single object in memory and use this object to access its methods.

Sample python code demonstrating singleton is given below:

class Mysingleton():
	#class variable holds singleton object's reference
    s = None
	
	#constructor
    def __init__(self):
        print "this will print only once!!!"
        self._name = None
		#set _name with setter
        self.name = "yuppii"

	#getter
    @property
    def name(self):
        return self._name

	#setter
    @name.setter
    def name(self,n):
        self._name = n

	#static method to get instance
    @staticmethod
    def getInstance():
		#if no object is created before, create new one
        if Mysingleton.s == None:
            Mysingleton.s = Mysingleton()

        return Mysingleton.s


print Mysingleton.getInstance().name
print Mysingleton.getInstance().name
print Mysingleton.getInstance().name
print Mysingleton.getInstance().name
print Mysingleton.getInstance().name
print Mysingleton.getInstance().name

You  should see an output like:

this will print only once!!!
yuppii
yuppii
yuppii
yuppii
yuppii
yuppii

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s