Wednesday, February 28, 2007

The Singleton Design Pattern

Definition: A singleton is a class that is instantiated exactly once (Gamma 1995 cited in Bloch 2001).

If you're sure that the class must be a singleton, use (Bloch 2001:11):

public class Singleton {
  public static final Singleton INSTANCE = new Singleton();

  private Singleton() {
  }
}

If youre not sure that class is a singleton, use (Bloch 2001:11):

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    
    private Singleton() {
    }
    
    public static Singleton getInstance() {
        return INSTANCE;
    }
}

If singleton should be serializable, provide a readResolve method.

The constructor private Singleton() is private to prevent instantiation.

Warning: Avoid double-checked locking. (http://www-128.ibm.com/developerworks/java/library/j-jtp03304/)

Serializable Singletons

If a singleton class should be serializable, add readResolve (Bloch 2001:11):

private Object Readresolve() throws ObjectStreamException {
return INSTANCE; // name of singleton object
}

See:

References

Resources

No comments: