Creational Design Patterns: Singleton

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.

cache
Singleton Example with Cache

 

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:

  1. Single Responsibility Principle
  2. Provides global access for the object

 

Hope this was useful, stay tuned for more on design patterns.

 

 

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