Singleton Method

Singleton Method

Singleton Method

The Singleton method is a design pattern that restricts the instantiation of a class to one object. It is a type of creational pattern that involves only one class to create methods and specified objects. It helps us to provide a global point of access to the instance created.

For example, the singleton method is like a country that has a single government, this government controls access and operations of itself within the country and while this government is in power, any attempt made to create another government will be forbidden.

The singleton method is implemented in Python code:

class Singleton:
    __shared_instance = "Python For Cybersecurity"
    @staticmethod
    def getInstance():
        """Static Access Methods """
        if Singleton.__shared_instance == "Python For Cybersecurity":
            Singleton()
        return Singleton.__shared_instance

    def __init__(self):
        """ Virtual Private Constructor"""
        if Singleton.__shared_instance != "Python For Cybersecurity":
            raise Exception("This is a singleton class !")
        else:
            Singleton.__shared_instance = self

if __name__ == '__main__':
    # create object of the singleton class
    obj = Singleton()
    print(obj)

    # pick the instance of the class
    obj = Singleton.getInstance()
    print(obj)
From the code above, a variable was defined to hold the single object that was instantiated and the constructor checks if there is an existing class and it raises an error(raise Exception(“This is a singleton class !”)). The getInstance() method is used to fetch the object and it checks for any existing instance available and returns it, otherwise it creates one and returns it.
The code is also known as the naive singleton, where it actually hides the constructor and implement a static creation method.
The output of the code is:
ProBook:~/InfosecAddicts/python_design_pattern$ python singleton.py
<__main__.Singleton instance at 0x7f17c582a710>
<__main__.Singleton instance at 0x7f17c582a710>
From the output, it is seen that the number of instances created is the same and there is no difference in the objects listed in the output.

Pros and Cons of the Singleton Method

Pros
  • Initializations
    • Whenever an object is created by a singleton method for the first time, it is been initialized.
  • Access to the Object
    • it has global access to the instance of the object.
  • Count of instance
    • classes can’t have more than one instance in the singleton method.
Cons
  • Unit testing process
    • Unit testing is very hard when the global state is introduced to the application.
  • Single responsibility Principle
    • Solving two problems in singleton method does not follow the singleton responsibility.
  • Multithread Environment
    • multithread wouldn’t create a singleton object several times.