May 5, 2010

Singleton pattern

In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.

Implementation
Implementation of a singleton pattern must satisfy the single instance and global access principles. It requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects. The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made protected (not private, because reuse and unit test could need to access the constructor). Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface
C#
///
/// Thread-safe singleton example created at first call
///

public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();

private Singleton() { }

public static Singleton Instance
{
get
{
return _instance;
}
}
}
Another method, that utilizes more of the functions of C#, could be used is as follows.




///
/// Thread-safe singleton example created at first call
///

public sealed class Singleton
{
///
/// Utilizes the get and set auto implemented properties.
/// Note that set; can be any other operator as long as it's
/// less accessible than public.
///

public static Singleton Instance { get; private set; }

///
/// A static constructor is automatically initialized on reference
/// to the class.
///

static Singleton() { Instance = new Singleton(); }
}
Example of use with the factory method pattern
The singleton pattern is often used in conjunction with the factory method pattern to create a system-wide resource whose specific type is not known to the code that uses it. An example of using these two patterns together is the Java Abstract Window Toolkit (AWT).

java.awt.Toolkit is an abstract class that binds the various AWT components to particular native toolkit implementations. The Toolkit class has a Toolkit.getDefaultToolkit() factory method that returns the platform-specific subclass of Toolkit. The Toolkit object is a singleton because the AWT needs only a single object to perform the binding and the object is relatively expensive to create. The toolkit methods must be implemented in an object and not as static methods of a class because the specific implementation is not known by the platform-independent components. The name of the specific Toolkit subclass used is specified by the "awt.toolkit" environment property accessed through System.getProperties().

The binding performed by the toolkit allows, for example, the backing implementation of a java.awt.Window to bind to the platform-specific java.awt.peer.WindowPeer implementation. Neither the Window class nor the application using the window needs to be aware of which platform-specific subclass of the peer is used.

Drawbacks
It should be noted that this pattern makes unit testing far more difficult[6], as it introduces global state into an application.

It should also be noted that this pattern reduces the potential for parallelism within a program, because access to the singleton in a multi-threaded context must be serialised, i.e. by locking.

Advocates of dependency injection would regard this as an anti-pattern, mainly due to its use of private and static methods.

Some have suggested ways to break down the singleton pattern using methods such as reflection in languages such as Java
There was an error in this gadget