Singleton

Singleton classes represent objects for which only one single instance should exist.

The important question here is this: will any actual harm come to the system if more than 1 object is created? If the answer is "no" (and it usually is), then there's no need whatsoever to use a singleton. If the answer is "yes", then you will need to consider it. The main point is that a singleton should only be used if it's really necessary.

Here's an article from Oracle describing them. This article, along with many others, reports many subtle problems with singletons. You should likely exercise care when using this pattern.

Example 1

This is the preferred style of implementing singletons. It uses a simple enumeration. It has no special needs for serialization, and is immune to clever attacks.


/** Preferred style for singletons. */
public enum SantaClaus {
  INSTANCE;
  
  /**Add some behavior to the object. */
  public void distributePresents(){
    //elided    
  }
  
  /** Demonstrate use of SantaClaus. */
  public static void main(String... aArgs){
    SantaClaus fatGuy = SantaClaus.INSTANCE;
    fatGuy.distributePresents();
    
    //doesn't compile :
    //SantaClaus fatGuy = new SantaClaus();
  }
} 

Example 2

Here's an alternate style. If you decide that the class should no longer be a singleton, you may simply change the implementation of getInstance.


public final class Universe {

  public static Universe getInstance() {
     return fINSTANCE;
  }

  // PRIVATE

  /**
  * Single instance created upon class loading.
  */
  private static final Universe fINSTANCE =  new Universe();

  /**
  * Private constructor prevents construction outside this class.
  */
  private Universe() {
    //..elided
  }
} 

Example 3

If the above style of singleton is to be Serializable as well, then you must add a readResolve method.


import java.io.*;

public final class EasterBunny implements Serializable {

  public static EasterBunny getInstance() {
     return fINSTANCE;
  }

  // PRIVATE

  /**
  * Single instance created upon class loading.
  */
  private static final EasterBunny fINSTANCE =  new EasterBunny();

  /**
  * Private constructor prevents construction outside this class.
  */
  private EasterBunny() {
    //..elided
  }

  /**
  * If the singleton implements Serializable, then this
  * method must be supplied.
  */
  private Object readResolve() throws ObjectStreamException {
    return fINSTANCE;
  }
} 

You might also consider defining your own tag interface for singleton classes.

See Also :
Private constructor
Implementing Serializable
Some classes need readResolve
Tag or marker interfaces
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -