What Is a Singleton Design Pattern?
- Singleton design pattern allows us to create only one instance of a class and make sure that there exists only one Object in JVM.
- Singleton class must have a public static method to get the instance of the class from anywhere in the application [from different classes, different packages, etc].
- Singleton class must have a private constructor to instantiate the object of the class.
- Singleton class must have a private static variable of the same class which is the only reference of the class[basically this variable will point to only Object of class].
Singleton Design Pattern
All these different implementation methods lead to one goal that is having a single instance of a class at any given point of time in JVM. Let’s see different implementation approaches for the Singleton design pattern
1. Eager Initialization :
- This is the simplest implementation of the singleton design pattern class. In this method, the private static variable of the same class [reference] is assigned the object of class at the time of loading the class into the JVM memory.
- This type of implementation is applicable to the scenarios when we always want the instance of the class.
Let’s see the program to understand this …
package com.vikram;
public class EagerSingleton {
//Only object created when class is loaded and theInstance is private static var pointing to it.
private static EagerSingleton theInstance = new EagerSingleton();
//private constructor
private EagerSingleton(){
}
//public method to return single instance of class .
public static EagerSingleton getInstance(){
return theInstance;
}
}
Eager Initialization
#desing-pattern #classloading #singleton-pattern #singleton-design-pattern #java-singleton-pattern