Site icon TestingDocs.com

Java Singleton Pattern

Overview

Java Singleton pattern is used to make a class that must be created only once across the Java application.  In other words, a singleton class should have only one instance running in the JVM. Let’s learn how to convert a class into a singleton in this tutorial.

Java Singleton Pattern

/*
 * Java Singleton Pattern Demo Program
 * Java Tutorials - www.TestingDocs.com
 */

public class JavaSingleton {

	private static JavaSingleton instance = null;

	// make the constructor private
	private JavaSingleton(){
		
	} 

	// getInstance() to ensure only one instance is created
	public static synchronized JavaSingleton getInstance(){
		if (instance == null)
		{
			instance = new JavaSingleton();
		}
		return instance;
	}

	public static void main(String arg[]){
		JavaSingleton first =new JavaSingleton();
		System.out.println("First Instance : "+ first.getInstance());
		JavaSingleton second=new JavaSingleton();
		System.out.println("Second Instance: " + second.getInstance());
	}
}

 

The constructor of the class is private, this is to prevent the clients from instantiating the objects of the class using the new operator.

The static synchronized getInstance() method creates and returns an instance of the class. The method controls the creation of the object and returns the already created instance if it’s already created. The method creates an instance of the class during the initial call and keeps returning the same instance.

Clients can invoke the method using the class name, For example:

JavaSingleton.getInstance();

Run the sample code and notice that the two objects of the class are exactly the same. We can invoke the getInstance() method multiple times, but this pattern ensures that only one instance of the class gets created in the Java program.

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version