Friday, November 18, 2011

Singleton Design pattern

Singleton design pattern

It is one of the design patterns to maintain the single instance of an object in a system. whenever object created using the new Object() code, one new instance created, if we call these, multiple instances are created in heap memory. Over the time the calls to the new objects grow, the size of the object size grows in the heap memory and it will cause performance overhead. To avoid this, we will make the one object creation for multiple calls and return the same object

Simple Implementation:-

  • private constructor to instantiate this class within this class only. not outside
  • a private static variable that is an instance of the same class
  • Declare Static method which checks static variable, if null, create an object else return the object.

Example:-

public class Singleton {
 /*
  * Initializing the static member variable as null
  */
 public static Singleton single = null;

 /*
  * private means, we can not create any object using new operator outside
  * this class
  */
 private Singleton() {

 }

 /*
  * this method always return same instance. you can make this method as
  * synchronized to create amultiple isntances by different thread at a time
  */

 public static Singleton getInstance() {
  if (single == null) {
   single = new Singleton();
  }
  return single;
 }

 /*
  * clone is not supported and throws exception if we make the clone of this
  * object
  * 
  * @see java.lang.Object#clone()
  */
 public Object clone() throws CloneNotSupportedException {
  throw new CloneNotSupportedException(
    "This is singleton class, cloning is not supported");
 }

 public static void main(String args[]) {
  /*
   * calling the multiple getInstance method always returns the same
   * instance
   */
  System.out.println("Object=1 " + getInstance());
  System.out.println("Object=2 " + getInstance());
 }
}

Advantage:-

This pattern maintains one instance of java object in heap memory of java virtual machine instead of creating multiple instances. Improve the performances and fewer objects created for heap memory

Related article