Monday, July 26, 2010

Implementing Singletons

There are a few ways to implement Singletons. Although you can get Singleton-like behavior with static fields and methods [for example, java.lang.Math.sin(double)], you gain more flexibility by creating an instance. With Singletons implemented as single instances instead of static class members, you can initialize the Singleton lazily, creating it only when it is first used. Likewise, with a Singleton implemented as single instance, you leave open the possibility of altering the class to create more instances in the future. With some implementations of the Singleton, you allow writers of subclasses to override methods polymorphically, something not possible with static methods.

Most commonly, you implement a Singleton in Java by having a single instance of the class as a static field. You can create that instance at class-loading time by assigning a newly created object to the static field in the field declaration, as seen in Listing 1.

Listing 1
public class MySingleton {
private static MySingleton _instance =
new MySingleton();

private MySingleton() {
// construct object . . .
}

public static MySingleton getInstance() {
return _instance;
}

// Remainder of class definition . . .

Alternatively, you can instantiate it lazily, on first demand, as seen in Listing 2. You keep the constructor private to prevent instantiation by outside callers.

Listing 2
public class MySingleton {
private static MySingleton _instance;

private MySingleton() {
// construct object . . .
}

// For lazy initialization
public static synchronized MySingleton getInstance() {
if (_instance==null) {
_instance = new MySingleton();
}
return _instance;
}
// Remainder of class definition . . .
}

Both Singleton implementations do not allow convenient subclassing, since getInstance(), being static, cannot be overridden polymorphically. Other implementations prove more flexible. While I don't have the space to describe alternative implementations in detail, here are a couple of possibilities:

No comments:

Post a Comment