by BehindJava

Real time example of a singleton design pattern in Java

Home » java » Real time example of a singleton design pattern in Java

In this tutorial we are going to learn about singleton design pattern in java.

Singleton Design Pattern in object oriented programming is a class that can have only one object i.e. single instance of a class at a time.

In terms of instantiation for a singleton class we use getInstance() method and for a normal class we use constructor.

For example, let’s say we have to define a class that has only one instance and provides global point of access to it where a class must ensure that only single instance should be created and single object can be used by all other classes.

There are two forms of singleton design pattern i.e.
Early Instantiation: creation of instance at load time.
Lazy Instantiation: creation if instance when required.

Advantages and uses of singleton design pattern are, saves memory because object is not created at each request where single instance is reused again and again. Singleton pattern is mostly used in multi-threaded and database applications.

Sample Code Snippet:

public class Singleton {
	
	private static Singleton singleton_instance=null;
	private Singleton()
	{
		connection();
	}
	public static Singleton getInstance()
	{
		if(singleton_instance==null) {
			singleton_instance =new Singleton();
		}
		return singleton_instance;
	}
	public void connection()
	{
		System.out.println("connected to database");
	}
	public static void main(String[] args)
	{
		Singleton s1;
		s1=Singleton.getInstance();
	}
}


Output:
connected to database