Python @ DjangoSpin

PyPro #71 Singleton Design Pattern

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Singleton Design Pattern in Python

Singleton Design Pattern in Python

Write a Python program to implement Singleton Design Pattern.

Singleton

# Let's create a class that maintains a shared data dictionary. This dictionary takes key-value pairs from each instance of the class and adds them to itself.
 
class DatabaseConfiguration():
    _sharedData = {}
    def __init__(self, **kwargs):
        self._sharedData.update(kwargs)             # update _sharedData dictionary with key-value pair(s) provided
    def __str__(self):
        return str(self._sharedData)                # return the _sharedData dictionary when object is printed
 
# Let's add a configuration detail in the form of a key-value pair to the sharedData dictionary
configDetailsOne = DatabaseConfiguration(database = "10.10.10.10")
# Printing the sharedData dictionary
print(configDetailsOne)                             # OUTPUT: {'database': '10.10.10.10'}
 
# Let's add a few more other configuration details to the sharedData dictionary
configDetailsTwo = DatabaseConfiguration(user = "userOne")
configDetailsThree = DatabaseConfiguration(password="userOne")
configDetailsFour = DatabaseConfiguration(serviceName="serviceOne")
 
# Let's take a look at what the sharedData dictionary now looks like.
print(configDetailsFour)                            # OUTPUT: {'password': 'userOne', 'database': '10.10.10.10', 'user': 'userOne', 'serviceName': 'serviceOne'}

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply