Reading Time: 2 minutesSingleton Design Pattern in Python
Singleton Design Pattern in Python
Design Patterns Home
What is it?
If you have taken the Python 101 course, you must be familiar with global variables. Global variables are declared using the global keyword, and can be accessed from any point in the program. Such variables are shared i.e. only one copy of these variables is maintained in the memory. The Singleton Design Pattern, is the object oriented equivalent of providing global variables. This is achieved by enabling the class to be instantiated once and only once i.e. only one object can be made of the class.
It is classified under Creational Design Patterns, since it addresses instantiation of classes.
Why the need for it: Problem Statement
The need for Singleton Pattern is felt in a couple of prominent situations, listed below:
- When logging needs to be implemented: The logger instance is shared by all the components of the system to log the messages.
- When a cache of information needs to be maintained for the purpose of being shared by various components in the system: By keeping the information in the shared object, there is no need to fetch the information from its original source every single time. An example of this scenario is configuration files.
- Managing a connection to a database.
Basically, the Singleton Pattern is needed when you need to manage a shared resource. The system needs to have a single instance of the concerned Singleton class in order to avoid conflicting request for the same resource.
How to implement it
class DatabaseConfiguration(): |
def __init__( self , * * kwargs): |
self ._sharedData.update(kwargs) |
return str ( self ._sharedData) |
configDetailsOne = DatabaseConfiguration(database = "10.10.10.10" ) |
configDetailsTwo = DatabaseConfiguration(user = "userOne" ) |
configDetailsThree = DatabaseConfiguration(password = "userOne" ) |
configDetailsFour = DatabaseConfiguration(serviceName = "serviceOne" ) |
See also: