Return to index

 

The Singleton

 

In software engineering, the Singleton is a design pattern used to restrict instantiation of a class to a single object. Here is the classic Singleton in outline.

public final class ClassicSingleton {

private static ClassicSingleton instance=null;

private ClassicSingleton() {

}

public static ClassicSingleton getInstance() {

if (instance==null) {

instance = new ClassicSingleton();

}

return instance;

}

}

The ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method. Hence to get the single instance one would write:

ClassicSingleton instance=ClassicSingleton.getInstance();

Notice that ClassicSingleton employs a useful technique known as 'lazy instantiation' to create the singleton - the singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that an instance is created only when (and if) needed.

This basic Singleton framework can serve you well, but in advanced situations one would need to consider multiple Thread access, the possibility of multiple classloaders and serialization as potential problems.


Return to index