What Is a Singleton Design Pattern?

  1. Singleton design pattern allows us to create only one instance of a class and make sure that there exists only one Object in JVM.
  2. 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].
  3. Singleton class must have a private constructor to instantiate the object of the class.
  4. 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].

Image for post

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 :

  1. 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.
  2. 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

Confused With Java Singleton Design Pattern? Have a Look at This Article.
1.75 GEEK