Design Pattern - Singleton
Singleton
Definition
Singleton pattern is a software design pattern that restricts the instantiation of a class to one single instance. This is useful when exactly one object is needed to coordinate actions across the system.
Common usage of Singleton pattern
- Single database object shared by different parts of the program
- Logging object.
- Replacement of global variables, since Singleton instances doesn't pollute namespace and has lazy initialization attribute.
Singleton with code
- We will define a single Singleton instance that will be instantiated statically.
- We will prevent Singleton instance from being created by default constructor by private access modifier. That way, there is no way to create singleton instance using new keyword.
- There must be a way to retrieve Singleton instance. We will create a static method getInstance(), that will enable us to retrieve the same Singleton instance whenever we request them.
Comments
Post a Comment