Singleton pattern purpose, strategy, usage and example
Singleton Pattern is one of the Gangs of Four Design Patterns and comes in Creational Design Patterns that restricts the instantiation of a class and ensures only one object of the class exists in the JVM (java virtual machine)
Purpose of singleton pattern
There should be only one instance allowed for a class and we should allow global point of access to that single instance.
Singleton pattern implementation strategy
- We hide the constructor of the class and don’t allow even a single instance for the class. This is done by declaring all the constructors of the class to be private.
- Define public static method (getSingletonInstance()) that returns the reference to the only instance of the class.
- The singleton instance is usually stored as a private static variable and the singleton instance is created when the variable is initialized.
Singleton pattern example
package com.sneppets.designpattern.creational.singleton; public final class Singleton { private static final Singleton singleInstance = new Singleton(); private Singleton() { } public static Singleton getSingleInstance() { return singleInstance; } }
Where exactly the singleton design pattern is used in real application?
We use this pattern for logger classes, configuration classes, caching classes etc.,