Cricinfo Live Scores

Monday, February 4, 2008

Design Pattern (GOF): Creational Pattern : Singleton

Sometimes it's appropriate to have exactly one instance of a class: window managers, print spoolers, and filesystems are prototypical examples. Typically, those types of objects—known as singletons—are accessed by disparate objects throughout a software system, and therefore require a global point of access. Of course, just when you're certain you will never need more than one instance, it's a good bet you'll change your mind.

The Singleton design pattern addresses all of the previous paragraph's concerns. With the Singleton design pattern you can:

  • Ensure that only one instance of a class is created
  • Provide a global point of access to the object
  • Allow multiple instances in the future without affecting a singleton class's clients

Although the Singleton design pattern—as evidenced below by the figure below—is one of the simplest design patterns, it presents a number of pitfalls for the unwary Java developer. This article discusses the Singleton design pattern and addresses those pitfalls.


EXAMPLE

A complete Singleton example is.

final public class ClassicSingleton { //final prevents inheritence

private ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
synchronized (this) // preventing multi-threaded instantiation
{
if(instance == null) {
instance = new ClassicSingleton(); // only one time created
}
}
return instance; // many times delivered
}

}

Author:

-----------------------

Kazi Masudul Alam

Software Engineer