Ben Chuanlong Du's Blog

It is never too late to learn.

Implement Singleton in Java

An implementation of the singleton pattern must:

  • ensure that only one instance of the singleton class ever exists;
  • and provide global access to that instance.

Typically, this is done by:

  • declaring all constructors of the class to be private;
  • and providing a static method that returns a reference to the instance.

The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called. The following is a sample implementation written in Java.

In [ ]:
public final class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

Singleton Implementation Using the Initialization-on-demond Holder Idiom

In [ ]:
public class Something {
    private Something() {}

    private static class LazyHolder {
        static final Something INSTANCE = new Something();
    }

    public static Something getInstance() {
        return LazyHolder.INSTANCE;
    }
}

Comments