Singleton pattern (Java)

From LiteratePrograms

Jump to: navigation, search
Other implementations: Java | Visual Basic .NET

The singleton pattern is designed to restrict instantiation of a class to one (or a few) instances.

The following SingletonObject class demonstrates one way to implement lazy creation of a singleton object. The class contains a self-referential class variable obj, which is used to represent the singleton object instance.

class SingletonObject {
  private static SingletonObject obj;
  private SingletonObject() { }

The getInstance class method provides access to the singleton object in a lazy manner, i.e. the singleton object is not actually instantiated until the first call to getInstance.

  public static synchronized SingletonObject getInstance() {
    if (obj == null) {
      obj = new SingletonObject();
    return obj;

We can test the singleton object by creating an executable that calls the SingletonObject.getInstance method twice, and checks to ensure that the two object references returned by that method represent the same object.

public class Singleton {
  public static void main(String[] args) {
    SingletonObject s01 = SingletonObject.getInstance();
    SingletonObject s02 = SingletonObject.getInstance();
    if (s01 == s02) {
      System.out.println("Reference equal");
    } else {
      System.out.println("Reference unequal");

Here are build and run scripts for both Linux and Windows.

java -cp . Singleton
@echo off
java -cp . Singleton
Download code