Friday, July 19, 2013

Singleton Design Pattern Example Program in Java


Definition:
The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Implementation:


1. Private static variable of the same class that is the only instance of the class. 
2. Private constructor to restrict instantiation of the class from other classes. 
3. Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.

/**
 * Singleton Program
 * @author Ranga Reddy
 * @date 19-Jul-2013
 *
 */

// Singleton.java

package com.ranga;

public class Singleton {
  // private static member
  private static Singleton singleton= null;

  // private constructor
  private Singleton() {

  }
  // public static method
  public static Singleton getSingletonInstance() {
    if(singleton == null){
      synchronized (Singleton.class) {
         if(singleton == null)
            singleton = new Singleton();
      }
    }
    return singleton;
  }
}
SingletonDemo.java

package com.ranga;

public class SingletonDemo {
  public static void main(String[] args) {
       Singleton singleton3 = Singleton.getSingletonInstance();
       Singleton singleton4 = Singleton.getSingletonInstance();
       if(singleton3 == singleton4){
          System.out.println("Single Instance");
       } else {
          System.out.println("Two Instances");
       }

  }
}

Output:
Single Instance
 
Some of the examples we can use in our applications.

Example 1 - Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are usually implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 - Configuration Classes

The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.


0 comments: