Wednesday, September 23, 2015

Effective Java - Item 3 : Enforce the singleton property with a private constructor or an enum type

A class is said to be singleton class if there is only one instance of it. Before release 1.5 there were 2 methods to implement this. One method was to make the constructor private which will be called only once to initialize a public static final field. This field will be the sole instance of the class.

// Singleton with public final field   
  public class Analyzer {   
   public static final Analyzer INSTANCE = new Analyzer ();   
   private Analyzer () { ... }  
  }

Another method is to provide a static factory method getInstance(). This method whenever invoked returns the same object reference ensuring no other instance of the class is created.

// Singleton with static factory  
  public class Analyzer {  
   private static final Analyzer INSTANCE = new Analyzer();  
   private Analyzer() { ... }  
   public static Analyzer getInstance() { return INSTANCE; }  
   public void analyze() { ... }  
 }

However if we need to make a singleton class serializable we would have to add a readResolve method to the class to preserve the singleton property.

// readResolve method to preserve singleton property   
  private Object readResolve() {   
   // Return the one true Analyzer and let the garbage collector   
   // take care of the Analyzer impersonator.   
   return INSTANCE;   
  }

The third and the best way to implement singleton classes is by making an enum type with a single element. It provides the serialization properties at the same time ensuring that there are no multiple instantiations.

// Enum singleton - the preferred approach   
  public enum Analyzer {   
   INSTANCE;   
  }

No comments:

Post a Comment