» » » Singleton Design Pattern in java

Problem:

  • Instead of creating multiple objects of same class having same data and wasting memory, degrading performance it is recommended to create only one object and use it multiple times.

Solution:

  •  Use Singleton Java Class.
  • Java class that allows us to create one object per JVM is is called as singleton java class.
  • The logger class of  Log 4J API is given as singleton java class.

Rules:

  • It must have only private constructors.
  • It must have private static reference variable of same class.
  • It must have public static factory method having the logic of singleton.
  • Static method should create and return only one object.
  • All these rules close all the doors of creating objects for java class and opens only one door to create object.
  • factory method where singleton logic is placed
  • The method of a class capable of creating and returning same class or other class object is known as factory method.

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.  
  22. return object;
  23.  
  24. }
  25.  
  26. }
     

  1. package instanceofjava;
  2.  
  3. public class SingletonObjectDemo {

  4. public static void main(String args[]) {
  5.  
  6.      SingletonClass s1= SingletonClass .getInstance();
  7.      SingletonClass s2= SingletonClass .getInstance();
  8.      System.out.println(s1.hashCode());
  9.      System.out.println(s2.hashCode());
  10.  
  11. }
  12. }

Output:

  1. getInstance(): First time getInstance was called and object created !
  2. Singleton(): Private constructor invoked
  3. 655022016
  4. 655022016


Make the Factory method Synchronized to prevent from Thread Problems:


  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static synchronized  SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.   
  22. return object;
  23.  
  24. }
  25.  
  26. }

Override the clone method to prevent cloning:

 

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static synchronized  SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.  else 
  22. return object;
  23.  
  24.  
  25. public Object clone() throws CloneNotSupportedException {
  26.  
  27. throw new CloneNotSupportedException();
  28.  
  29. }
  30.  
  31. }

Eager Initialization:

  • In eager initialization object of the class will be created when class loading itself its easy way to create singleton but its having one disadvantage that even though nobody needs it still it creates object.

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object= new SingletonClass ();
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static SingletonClass getInstance()
  12. {
  13.  
  14. return object;
  15.  
  16. }
  17.  
  18. }
     


Lazy Initialization:

  • When ever client needs object it will check for whether object is created or not if not it will create otherwise it will return created object
  • First basic example shows lazy initialization.


Static Block Initialization:

  • This is similar to eager initialization except that in this we create object in static block and we can place exception logic.

  1. package com.instanceofjava;
  2.  
  3. public class StaticBlockSingleton {
  4.  
  5. private static StaticBlockSingleton object;
  6.  
  7. private StaticBlockSingleton(){}
  8.  
  9.     //static block initialization for exception handling
  10. static{
  11.  
  12.  try{
  13.  
  14.             object = new StaticBlockSingleton();
  15.  
  16.         }catch(Exception e){
  17.  
  18.             throw new RuntimeException("Exception occured in creating singleton object");
  19. }
  20. }
  21.  
  22. public static StaticBlockSingleton getInstance(){
  23.         return object;
  24. }
  25.  
  26. }


Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

2 comments for Singleton Design Pattern in java

Select Menu