How to Create a Singlton Class in Java by Example?

Singleton: Exactly one instance of a class. Define a class that has only one instance and provide a global point of access of it.

Create a class singleton is very important in real time project. The Singleton's purpose is to control object creation, limiting the number of objects to one only. If we are creating a object of a class again and again , that will definitely increase the memory and finally our application will get slow.

For Example: If we have restriction that we can create only one instance of a database connection. In this case we will create only one object of database and used everywhere.

Implementation of Singleton class:

Singleton.java

  1. package com.java.deepak.singleton;  
  2.   
  3. public class Singleton  
  4. {  
  5.     private static Singleton instance;  
  6.   
  7.     private Singleton()  
  8.     {  
  9.     }  
  10.   
  11.     public synchronized static Singleton getInstance()  
  12.     {  
  13.         if ( instance == null )  
  14.         {  
  15.             instance = new Singleton();  
  16.             System.out.println( "New Object Created...!!!" );  
  17.         }  
  18.         else  
  19.         {  
  20.             System.out.println( "Object Already in Memory..." );  
  21.         }  
  22.         return instance;  
  23.     }  
  24. }   
  • We will make constructor as private. So than we can not create an object outside of a class.

  • Create a private method to create a object of a class. By using this method, we will create an object outside of class.

SingletonClient.java

  1. package com.java.deepak.singleton;  
  2.   
  3. public class SingletonClient  
  4. {  
  5.     public static void main( String[] args )  
  6.     {  
  7.         Singleton s1 = Singleton.getInstance();  
  8.         Singleton s2 = Singleton.getInstance();  
  9.     }  
  10. }  
Here we are calling singleton class two times.

Output:


output

In output, we can see that when we call method first time then new object will create but when we call second time then existing object will return.