Saturday, 25 February 2017

Singleton design pattern in java

Singleton Pattern says that just"define a class that has only one instance and provides a global point of access to it".

In other words, a class must ensure that only single instance should be created and single object can be used by all other classes.

Advantages of Singleton design pattern


Memory saving: Saves memory as object is created only once for all request. Single instance is used again and again.

Usage of Singleton design pattern


It's used in
  • Mutlti threaded application
  • Database application

It is used in logging, caching, thread pools, configuration settings etc.

How to create Singleton design pattern ?


To create the singleton class, we need to have static member of class, private constructor and static factory method.
  • Static member: It gets memory only once because of static, it contains the instance of the Singleton class.
  • Private constructor: It will prevent to instantiate the Singleton class from outside the class.
  • Static factory method: This provides the global point of access to the Singleton object and returns the instance to the caller.


Types of  singleton design pattern


There are two types of singleton design pattern:
  • Early Instantiation: Creation of instance at load time.
  • Lazy Instantiation: Creation of instance when required.

Early Instantiation Example:
package com.rd;

public class SingletonPattern {

 private static SingletonPattern object= new SingletonPattern(); //at load time
 private SingletonPattern(){
  
 }
 public static SingletonPattern getInstance(){
  return object;
 }
 
 public void sayHi(String name){
  System.out.println("Hi "+name);
 }
}
package com.rd;

public class TestSingleton {

 public static void main(String[] args) {
  SingletonPattern object = SingletonPattern.getInstance();
  object.sayHi("Ankur");

 }

}
 

Lazy Instantiation Example:

package com.rd;

public class SingletonPattern {

 private static SingletonPattern object= null;
 private SingletonPattern(){
  
 }
 public static SingletonPattern getInstance(){
  if(object==null){
   object = new SingletonPattern(); // at request time
  }
  return object;
 }
 
 public void sayHi(String name){
  System.out.println("Hi "+name);
 }
}
package com.rd;

public class TestSingleton {

 public static void main(String[] args) {
  SingletonPattern object = SingletonPattern.getInstance();
  object.sayHi("Ankur");

 }

}



No comments:

Post a Comment