Singleton Pattern Article Index for
Singleton
Website Links For
Singleton
 

Information About

Singleton Pattern




The singleton pattern is implemented by creating a Class with a method that creates a new instance of the object 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 either private or protected. 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.

The singleton pattern must be carefully constructed in Multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.

The classic solution to this problem is to use Mutual Exclusion on the class that indicates that the object is being instantiated.


CLASS DIAGRAM



EXAMPLE IMPLEMENTATIONS


A correct threadsafe Java Programming Language Lazy-loaded solution known as the "Initialization On Demand Holder" idiom suggested by Bill Pugh follows:

public class Singleton '''{'''
// Private constructor suppresses generation of a (public) default constructor
private Singleton() '''{}'''

public static Singleton getInstance() '''{'''
return SingletonHolder.instance;
}

private static class SingletonHolder '''{'''
private static Singleton instance = '''new''' Singleton();
}
}

An incorrect lazy-loaded example follows. It is left here to demonstrate a common error in Java. It is based on the Q&A link found below, modified for multi-threading, however, it is still vulnerable to the '' Double-checked Locking '' anti-pattern, also found below:

public class Singleton '''{'''
private static Singleton INSTANCE = '''null''';

// Private constructor suppresses
private Singleton() '''{}'''

//synchronized creator to defend against multi-threading issues
//another if check here to avoid multiple instantiation
private synchronized static void createInstance() '''{'''
if (INSTANCE == null) '''{'''
INSTANCE = new Singleton();
}
}

public static Singleton getInstance() '''{'''
if (INSTANCE == null) createInstance();
return INSTANCE;
}
}

A possible C++ solution using Curiously Recurring Template Pattern (also known as Meyers singleton) where the singleton is a static local object (note: this solution is not thread-safe and is designed to give an idea of how singletons work rather than a solution usable in large-scale software project).

template<'''typename''' T> '''class''' Singleton
{

public:
static T& Instance()
{
static T theSingleInstance; //assumes T has a default constructor
return theSingleInstance;
}
};

class OnlyOne : '''public''' Singleton
{
//..rest of interface defined here
};

An example REALbasic solution uses a "Shared" method (available only in REALbasic 2006r1 or greater) to provide the instance. Note that this is thread-safe because REALbasic uses a cooperative threading model (instead of a preemptive one).

Class Singleton
Protected Sub Constructor()
// Initialization code defined here
End Sub
Shared Function Instance() '''as''' Singleton
static s '''as new''' Singleton
return s
End Function
End Class
In a Prototype-based Programming language, where objects but not classes are used, a "singleton" simply refers to an object without copies or that is not used as the prototype for any other object.

Singleton (LoadBalancer)
defines an Instance operation that lets clients access its unique instance. Instance is a class operation responsible for creating and maintaining its own unique instance. Ensure a class has only one instance and provide a global point of access to it.


EXAMPLE OF USAGE 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 Windowing Toolkit (AWT).

is an Abstract Class that Binds the various AWT components to particular native toolkit implementations. The Toolkit class has a 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 Method s 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 .

The binding performed by the toolkit allows, for example, the backing implementation of a to bound 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.


SEE ALSO



EXTERNAL LINKS