Wednesday, 27 June 2012

Best Way to Implement Singleton in 1.5 and above


class SingleTon implements Serializable {

   public static final SingleTon INSTANCE = new SingleTon(); 
   private SingleTon() {
   }
   String name;
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
  
   private Object readResolve() {   //To Maintain Single Instance even in de-serialization
      return INSTANCE;
   }
}

public class OldSingleTone {
   public static void main(String... args) {
      SingleTon single = SingleTon.INSTANCE;
      single.setName("BNP");
      System.out.println(single.getName());
   }
}

------------------------------------------------------------------------------------------------------------------------------------------------------------

In Java 1.5

enum SingleTon {
   INSTANCE;

   String name;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

public class OldSingleTone {
   public static void main(String... args) {
      SingleTon single = SingleTon.INSTANCE;
      single.setName("BNP");
      System.out.println(single.getName());
   }
}

------------------------------------------------------------------------------------------

If you want a SingleTon class as Serializable you need to override readResolve Method but in Enum its too simple.....

"a single-element enum type is the best way to implement a singleton."

Note : Enums are inherently Serializable... (http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Enum.html)