Posts

Showing posts from July, 2022

Java Design pattern

 Singleton Design pattern :-  it's Creational Design Pattern as we need to have only one instance of our class for Ex:- Logger,DBConnector. SingleObject class have its constructor as private and have a static instance of itself. Code:-  public class Singleton { private static Singleton object; private Singleton() { } public static synchronized Singleton getInstance() { if (object == null) object = new Singleton(); return object; } } Eager Initialization :-  public class Singleton { private static Singleton object = new Singleton(); private Singleton() { } public static Singleton getInstance() { return object; } } Double checked Locking :-  public class Singleton { private static volatile Singleton obj = null; private Singleton() { } public static Singleton getInstance() { if (obj == null) { synchronized (Singleton.class) { if (obj == null) obj = new Singleton(); } } return obj; } } W