Singleton pattern is one of the most commonly used software design pattern. It comes under creational pattern. By Manoj Singh Saun.
The singleton pattern restricts the instantiation of a class to one “single” instance. It is useful when exactly one object is needed to coordinate actions across the system. e.g. database connection is a good example of singleton pattern.Creating database connection is a much heavier and more expensive job from a performance point of view.So It is better that a single connection is share by multiple objects.
The singleton pattern can be implemented in many ways. An implementation of the singleton pattern must follow the following points:
- It should ensure that only one instance of the singleton class ever exists
- It should provide global access to that instance
The article further describes and provides code examples for:
- The classic way to create Singleton pattern (not thread safe)
- Another example of Singleton using Eager Instantiation (thread safe)
- Example of Singleton using synchronized (thread safe)
- Example of Singleton using double checked locking (thread safe; the field needs to be volatile to provide consistency)
Straightforward with detailed code explanation for each method used. Great!
[Read More]