Wednesday, 21 November 2012

Singlton Class and its Use in Java 

  • Ensure that only one instance of a class is created
  • Provide a global point of access to the object
  • Allow multiple instances in the future without affecting a singleton class's clients

public class ClassicSingleton {
   private static ClassicSingleton instance = null;
   protected ClassicSingleton() {
      // Exists only to defeat instantiation.
   }
   public static ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }
}
 
In JDK which is written using singleton pattern, here are few of them:
  • Java.lang.Runtime with getRuntime() method
  • Java.awt.Toolkit with getDefaultToolkit()
  • Java.awt.Desktop with  getDesktop()