Singleton Design Pattern - My Empty Mind

We Discuss

  •   Truth
  •   Products
  •   BigData
  •  Technology

Hot

Post Top Ad

Your Ad Spot

Singleton Design Pattern


Singleton design pattern belongs to creational design pattern family. this pattern is used to create object. In this pattern only one object is created across java virtual machine (JVM) and this object can be used by all classes.

There are many ways we can implement this pattern.

1) Eager Initialization: In this method of creation, Object of class is created when it is loaded to memory by JVM. this can be done by assigning instance to reference variable directly.

 // Java code to create singleton class by   
 // Eager Initialization  
 public class SingletonTest   
 {  
  // public instance initialized when loading the class  
  public static SingletonTest obj = new SingletonTest();  
  private SingletonTest()  
  {  
   // code for private constructor  
  }  
 }  

2) Using Static Block : this is same as Eagar Initialization , the only difference is Object is created in static block. it will help to handle exception , if any occured.

 // Java code to create singleton class  
 // Using Static block  
 public class SingletonTest   
 {  
  // public instance  
  public static SingletonTest obj;  
  private SingletonTest()   
  {  
   // private constructor  
  }  
  {  
   // static block to initialize instance  
   obj = new SingletonTest();  
  }  
 }  






No comments:

Post a Comment