Wednesday, April 15, 2009

Create singleton classes in Java

The Java singleton design pattern restricts the creation of a class to one object. There are two ways to create a singleton class in Java. While both approaches are correct, but deciding which approach to use requires some discussion.

Let's see how to create a singleton class Foo, which has one method doFoo that prints a string message to the standard output stream. By being a singleton class, at anytime only one instance of this Foo class can be instantiated by a single Java classloader.

Approach 1: Use enum to create a singleton class
public enum Foo {
INSTANCE;

public void doFoo(){
   System.out.println("Hello World!);
}

// Usage Example 1:
// Gets the singleton Foo object, and calls doFoo
Foo.INSTANCE.doFoo();


Approach 2: Use private static variable and static factory method to create a singleton class

public final class Foo {

private static final Foo singleton = new Foo();

// Make the default constructor private
private Foo(){
   // no code
}

public static final Foo getInstance(){
   return Foo.singleton;
}

// Usage Example 2
// Gets the singleton Foo object, and calls doFoo
Foo.getInstance().doFoo();


In the two usage examples, the calls to Foo.doFoo look very similar. But, technically they are very different. In the first example, we access the singleton object through an enum instance of the class (i.e., Foo.INSTANCE). In the second example, we access the singleton object through a static factory method, which returns the static variable singleton. This private variable is statically created when a Java classloader loads the Foo class.

So which approach is more preferred when writing a Java singleton class? Some developers prefer the second approach because it is the de facto approach to create a singleton class since the birth of the Java programming language. They also argue that since all experienced Java developers are familiar with this approach, software programs that adopt this approach should be more maintainable and readable.

Personally I prefer the first approach. First, it's easy to create singleton classes using enum -- if you know how to create an enum class, then you know how to create singleton. Second, it eliminates the possibility for multiple objects of the same singleton class to be created through a careless custom Java serialization implementation.

0 comments:

Post a Comment