Testing the Singleton Pattern

The Singleton pattern guarantees uniform and controlled access to a unique instance of an object.2 It acts as the object-oriented stand-in for a global variable in the cases in which such is warranted. In its purest use, it corresponds to a real and unique physical resource. It is often used to represent something that is unique to the application, such as an entry point to a remote service or an application registry.

2. Do not confuse the Singleton pattern with the broader concept of a singleton object, an object of which only one exists. The Singleton pattern is one way to ensure you have a singleton object, but there are other reasonable approaches.

There are several ways to implement singletons. A typical implementation in Java3 is shown in Listing 10-1. Unlike in C++ or C#, you cannot create a reusable singleton base class in Java, so the language constraints result in continuous reimplementation of the pattern where it is needed.

3. With a quick search, you will find considerable debate about the “right” way to implement the Singleton pattern in any given language. In Java alone, the behavior of static member initialization and changes in the memory model with Java 5 fuel much discussion. There are similar issues in other languages, such as the C++ issues mentioned in Design Patterns [DP]. For the most part, these variations are not material to discussions about how to test singletons although testability may coax you away from some implementations.

Listing 10-1: A typical Java implementation of the Singleton pattern

public final class Singleton {
  private static Singleton instance = null;

  private Singleton() {
    // Initialization
  }

  public static synchronized Singleton getInstance() {
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
  public void doSomething() {
    // What the class does
  }
}

Let’s quickly walk through this. First, we have the class definition itself, which declares that the class cannot be subclassed, preventing the unique instance from being more specialized. Next, we have the class variable instance that references the unique instance of the class. The private constructor prevents uncontrolled construction of the class, making the getInstance() method the only, and thread-safe, way to obtain an instance of the class. Finally, the class has some additional methods to accomplish its purpose in the application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.134.17