Monday, February 4, 2008

Singleton objects

Class Diagram representing a singleton

Traditional Way

public class Singleton
{
private final static Singleton INSTANCE = new Singleton();
// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}


In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist. It is also considered an anti-pattern since it is often used as a euphemism for global variable.


The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation. Façade objects are often Singletons because only one Façade object is required.
State objects are often Singletons.


Singletons are often preferred to global variables because:

1. They don't pollute the global namespace (or, in languages with namespaces, their containing namespace) with unnecessary variables.
2. They permit lazy allocation and initialization, where global variables in many languages will always consume resources.

For more information visit

No comments: