Ensure a class only has one instance, and provide a global point of access to it.

Participants

The method for accessing the unique instance may use lazy creation - the instance is not created until the first time the method is invoked.

Implementation

Here is a singleton class with lazy creation.

    public class Singleton {

      protected Singleton() {
        // initialization code
      }

      // instance methods

      private static Singleton theSingleton;

      public static Singleton createSingleton() {
        if (theSingleton == null) {
          theSingleton = new Singleton();
        }
        return theSingleton;
      }

    }