Singleton is needed when you want only one object to be instantiated from a class. Singleton ensures that class has only one instance, and that instance has global access, you can call it object oriented way of initializing global variable. An example for this would be, for our cake website we keep a cache that is a singleton which will have all information, In this way we would not need to retrieve information from its original source.

Following is the implementation
""" Creational Pattern - Singleton """
class CakeApp():
_cake_shared_details = {}
def __init__(self):
# Creating a dict
self.__dict__ = self._cake_shared_details
class CacheSingletonImplementation(CakeApp):
def __init__(self,**kwargs):
CakeApp.__init__(self)
# Updating dict each time a new cake is added to the CakeApp
self._cake_shared_details.update(**kwargs)
def __str__(self):
# Returning the dict
return str(self._cake_shared_details)
#Creating singleton object
cake = CacheSingletonImplementation(Vanilla='$10')
# Printing object
print(cake)
>>{'Vanilla': '$10'}
Singleton helps solving two problems:
- Single Responsibility Principle
- Provides global access for the object
Hope this was useful, stay tuned for more on design patterns.
Leave a comment