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)
ProBook:~/InfosecAddicts/python_design_pattern$ python singleton.py <__main__.Singleton instance at 0x7f17c582a710> <__main__.Singleton instance at 0x7f17c582a710>
Pros and Cons of the Singleton Method
- 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.
- 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.