Design Patterns — Zero to Hero — Singleton Pattern

Photo by Luca Bravo on Unsplash

The Singleton Pattern ensures a class has only one instance, and provide a global point of access to it.

public Singleton{//Private Constructor
private Singleton(){
}// getInstance method will return Singleton class object
public static Singleton getInstance(){
//Implementation for creating new Singleton class objects}}
Singleton.getInstance();
public Singleton{// This static variable will hold the one instance of the      class Singletonprivate static Singleton uniqueInstance;//Private Constructor
private Singleton(){
}// getInstance method will return Singleton class object
public static Singleton getInstance(){
//Implementation for creating new Singleton class objects if(uniqueInstance == null){
uniqueInstance = new Singleton();
System.out.println("New Singleton Object Instantiated")
}
return uniqueInstance;
}}

Before know about Multi-Thread execution, You should have an understanding of handling/creating Threads in Java. Then only you could be able to understand this without any hustle. I am attaching reference YouTube videos so that you can refer it too.

New Singleton Object Instantiated
New Singleton Object Instantiated
public Singleton{// This static variable will hold the one instance of the      class Singletonprivate static Singleton uniqueInstance;     //Private Constructor
private Singleton(){
} // getInstance method is set to synchronized, therfore the Threads will wait till the getInstance method is unlocked by other thread
public static synchronized Singleton getInstance(){
//Implementation for creating new Singleton class objects if(uniqueInstance == null){
uniqueInstance = new Singleton();
System.out.println("New Singleton Object Instantiated")
}
return uniqueInstance; }}
public class Singleton {//This one is a Thread-safe when instantiating class object while assigning it to the static initializer  

private static Singleton uniqueInstance = new Singleton();
private Singleton(){}private static Singleton getInstance(){
return uniqueInstance
}
}
public Singleton{       // Volatile keyword ensures multiple threads handle the variable correctly when it initilized         private volatile static Singleton uniqueInstance;       //Private Constructor
private Singleton(){}
public static Singleton getInstance(){
if(uniqueInstance == null){
synchronized (Singleton.class){ if (uniqueInstance == null){
uniqueInstance = new Singleton();
System.out.println("New Singleton Object Instantiated")
}
} }
return uniqueInstance;
}}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store