What is singleton class in Java?





What is singleton class in Java ?


Single class is described as a class for which you can create only one object. For any

Java class if you allow to create only one object called a singleton class. So there are some following points about singleton class:


  1. Singleton class is perfect example of using private constructor(this concept came under OOPS concept)

  2. Examples of singleton class are: Runtime,BussinessDelegate,ServiceLocator.



Advantages of Singleton Class:


  1. Memory Utilization: Consider the case “creating one object and sharing between all of them, it means if the requirement is the same for all resources, so they can simply use the same object example as: Database connection. If you want to connect only with database so use only the same object ,there is no need to create a new object using the same object for the same purpose.


  1. Performance improvement:Hence you are creating only one object for the same requirement performance wise already improvement occurs in a system.Because we are not creating multiple objects for the same requirement,we are creating only one object. So permanence will improve.

   


Creating Singleton classes:


You cannot create singleton classes using constructor,because if you are allowed to create that you can create as many objects as you need.


How to create our own singleton class?


There are two approaches you can follow to create your own singleton class-


  1. Using private constructor- 


class  MySingleton class{


private static MySingleton obj  = new MySingleton();


private MySingleton(){}

public static MySingleton getMySingletonObj(){  //Factory method


  Return obj;

}

 

}


For creating object when you need (every time you get same object)


   MySingleton obj1 = MySingleton.getMySingletonObj();

   MySingleton obj2 = MySingleton.getMySingletonObj();

   MySingleton obj3 = MySingleton.getMySingletonObj();


  1. Using second approach(create object when needed):

            

 

class  MySingleton class{


private static MySingleton obj  = null;


private MySingleton(){}

public static MySingleton getMySingletonObj(){  //Factory method


if(obj==null){

obj = new MySingleton();


}

  return obj;

}

 

}


For creating object when you need (every time you get same object)


   MySingleton obj1 = MySingleton.getMySingletonObj();

   MySingleton obj2 = MySingleton.getMySingletonObj();

   MySingleton obj3 = MySingleton.getMySingletonObj();


At any point of time we can create only one object for MySingleton class. Hence this class is singleton class.


Comments