Posts

Showing posts from June, 2023

Singleton Pattern Examples and Implementation

Implementation of Singleton Design pattern   To implement a singleton pattern, we have different approaches, but all of them have the following common concepts.   --Private constructor to restrict instantiation of the class from other classes.   --Private static variable of the same class that is the only instance of the class.   --Public static method that returns the instance of the class, this is the global access point for the outer world to get the instance of the singleton class.   Let’s put them in Action.     Approach-1    Eager Initialization   In eager initialization, the instance of the singleton class is created at the time of class loading. The drawback to eager initialization is that the method is created even though the client application might not be using it. Here is the implementation of the static initialization singleton class   public class EagerInitializedSingleton {   private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();     /