What
A design pattern that restricts a class to instantiate only a single object, or instance. This is useful when exactly one object is needed to coordinate actions across the system.
How
Python
Java
- Private static variable of the same class that is the only instance of the class.
- Private constructor to restrict instantiation of the class from other classes.
- Public static method that returns the instance of the class, this is the global access point for the outer world to get the instance of the singleton class.
Why
Avoid inconsistent behavior if different parts of the program accessed different instances.
Ensure that there’s only one instance of the settings class that all parts of the program can access.
Links
- Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade, etc.