A singleton is a class that can be instantiated once and only once. But, why do you need them? If you are creating a class for a set up configuration and use the old fashioned class constrution, you may end up creating numerous configuration objects while you need only one copy. This singleton design pattern comes handy in this situation. You should also use Singleton when creating RMI lookup and creating JDBC connection.

How to create Singleton object?
1. Block off accessing to all constructors by making access modifier of default construtor as private.
2. Provide static method for getting an instance of the singleton.
3. Prevent cloning (usually developers forget to do; as every object inherits clone() method)

Implementation:
public class SingletonObject {

  private static SingletonObject ref;

  private SingletonObject() {
  }

  public static SingletonObject getSingletonObject() {
    if (ref == null)
      ref = new SingletonObject();
    return ref;
  }

  public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
  }

}

Reference: http://www.javacoffeebreak.com/articles/designpatterns/index.html

Advertisements