Singleton Design pattern

Singleton design pattern is one of the design pattern to maintain the single instance of object in a system. whenever object created using new Object() code, one new instance created, if we call this multiple instances are created in heap memory. Over the time the calls to the new objects grows, size of the object size grows in the heap memory and it will cause performance overahead. To avoid this, we will make the one object creation for multiple calls and return the same 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 less objects created for heap memory

No comments:

Post a Comment

Note: only a member of this blog may post a comment.