Singleton design pattern


Definition


One instance of a class or one value accessible globally in an application.

Where to use & benifits?


  • Ensure unique instance by making default constructor private and create only one object.
  • Default constructor is private so no class can extend it(no subclass).
  • Not implementing Serializable so cannot create duplicate instance by read/write to file/stream.
  • Not implementing Clonable interface so cannot be cloned.
  • Make a method or a variable public or/and static.
  • Access to the instance by the way you provided.
  • Well control the instantiation of a class.
  • Define one value shared by all instances by making it static.
  • Related patterns include
    • Factory Pattern, which is a layer higher than a factory method.
    • Template method, which defines a skeleton of an algorithm to defer some steps to subclasses or avoid subclasses
    • Prototype, which creates a new object by copying an instance, so it reduces subclasses.
    • Abstract Factory , which is a layer higher than a factory method

Example:

Following are few simple examples just to show the concept.

Example: Lazy initialization


SingletonLazyInitialization.java
package com.meritmix.blog.designPattern.singleton;
/**
 * @author Ravi Yadav
 * This is copyright content of MeritMix.com
 * blog address is blog.meritmix.com 
 */
public class SingletonLazyInitialization {
 private static SingletonLazyInitialization INSTANCE=null;
 private SingletonLazyInitialization() {
  // hide the default constructor so that other classes cannot create
  // object of this class
 }
 public static SingletonLazyInitialization getInstance() {
  //use double check method
  if(INSTANCE == null){
   synchronized (SingletonLazyInitialization.class) {
    if(INSTANCE == null){
     INSTANCE = new SingletonLazyInitialization();
    }
   }
  }
  return INSTANCE;
 }
 
 //Now lets test this
 public static void main(String[] args) {
  
  for (int i = 0; i < 10; i++) {
   final int count =i;
   new Thread(){
    public void run() {
     System.out.println("i:"+count+" hashcode: "+ 
SingletonLazyInitialization.getInstance().hashCode());
    };
   }.start();
  }
 }
}


Below same hashcode on each call to getInstance() method indicates that only one object of the class exists irrespective of how many times you call the getInstance() method.

Output:
i:1 hashcode: 778966024
i:3 hashcode: 778966024
i:0 hashcode: 778966024
i:6 hashcode: 778966024
i:2 hashcode: 778966024
i:7 hashcode: 778966024
i:4 hashcode: 778966024
i:5 hashcode: 778966024
i:9 hashcode: 778966024
i:8 hashcode: 778966024


Example: Eager initialization


SingletonEagerInitialization.java
package com.meritmix.blog.designPattern.singleton;

/**
 * @author Ravi Yadav
 * This is copyright content of MeritMix.com
 * blog address is blog.meritmix.com 
 */
public class SingletonEagerInitialization {
private static SingletonEagerInitialization INSTANCE=new SingletonEagerInitialization();
 private SingletonEagerInitialization() {
  // hide the default constructor so that other classes cannot create
  // object of this class
 }
 public static SingletonEagerInitialization getInstance() {
  // instance was created at class load time so no need to 
  // synchronize it.
  return INSTANCE;
 }
 
 //Now lets test this
 public static void main(String[] args) {
  
  for (int i = 0; i < 10; i++) {
   final int count =i;
   new Thread(){
    public void run() {
     System.out.println("i:"+count+" hashcode: "+ 
SingletonEagerInitialization.getInstance().hashCode());
    };
   }.start();
  }
 }
}


Again! same hashcode so only one object was created.

Output:
i:0 hashcode: 1414159026
i:2 hashcode: 1414159026
i:1 hashcode: 1414159026
i:3 hashcode: 1414159026
i:4 hashcode: 1414159026
i:5 hashcode: 1414159026
i:6 hashcode: 1414159026
i:7 hashcode: 1414159026
i:8 hashcode: 1414159026
i:9 hashcode: 1414159026


Related patterns :
  • Factory Pattern, which is a layer higher than a factory method.
  • Template method, which defines a skeleton of an algorithm to defer some steps to subclasses or avoid subclasses
  • Prototype, which creates a new object by copying an instance, so it reduces subclasses.
  • Abstract Factory , which is a layer higher than a factory method

No comments:

Post a Comment