Singleton pattern (Java)

From LiteratePrograms

(Redirected from Singleton (Java))
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.

<<SingletonObject>>=
class SingletonObject {
  private static SingletonObject obj;
  private SingletonObject() { }
getInstance
}

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.

<<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.

<<Singleton.java>>=
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");
    }
  }
}
SingletonObject

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

<<build_and_run.sh>>=
#!/bin/bash
javac Singleton.java
java -cp . Singleton
<<build_and_run.bat>>=
@echo off
javac Singleton.java
java -cp . Singleton
Download code
Views