Singleton pattern
Salithra Pathirana 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.[1][2][3][4][5][6]
In C++ it also serves to isolate from the unpredictability of the order of dynamic initialization, returning control to the programmer.
Common uses
- The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.
- Facade objects are often Singletons because only one Facade object is required.
- State objects [?] are often Singletons.
- Singletons are often preferred to global variables because:
Class diagram

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, it really has to be a singleton.
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.
Example implementations
Java
The Java programming language solutions provided here are all thread-safe but differ in supported language versions and lazy-loading.
Traditional simple way
This solution is thread-safe without requiring special language constructs, but it may lack the laziness of the one below. The INSTANCE is created as soon as the Singleton class is initialized. That might even be long before getInstance() is called. It might be (for example) when some static method of the class is used. If laziness is not needed or the instance needs to be created early in the application's execution, or your class has no other static members or methods that could prompt early initialization (and thus creation of the instance), this (slightly) simpler solution can be used:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
The solution of Bill Pugh
University of Maryland Computer Science researcher Bill Pugh has written about the code issues underlying the Singleton pattern when implemented in Java.[8] Pugh's efforts on the "Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. The technique known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines.
The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile
or synchronized
).
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Traditional simple way using synchronization
This solution is thread-safe in Java 5.0 and later:
public class Singleton {
// volatile is needed so that multiple thread can reconcile the instance
// semantics for volatile changed in Java 5.
private volatile static Singleton singleton;
private Singleton(){}
// synchronized keyword has been removed from here
public static Singleton getSingleton(){
// needed because once there is singleton available no need to acquire
// monitor again & again as it is costly
if(singleton==null) {
synchronized(Singleton.class){
// this is needed if two threads are waiting at the monitor at the
// time when singleton was getting instantiated
if(singleton==null)
singleton= new Singleton();
}
}
return singleton;
}
}
Prior to Java 5.0 this solution would not be thread safe, see: [1].
C++
// Header file (.h)
//
// A minimalist Singleton.
//
// This version does nothing more than enlist the help of the compiler
// to prevent additional instantiations, but is otherwise equivalent
// with a simple global variable.
//
// It has multiple caveats that may very well rule it out as a solution,
// problems that are actually more challenging and perhaps the main
// reason to use a Singleton pattern in C++ (but a less simplistic one).
//
// Firstly, if this singleton exists in some library. Users that use that library
// will have an instance of the singleton during application execution
// whether it is used or not.
//
// Secondly, is the case of file static dependency. For example, assume that
// the Singleton is some abstract factory for the type BaseType, and
// implements a method create. As the order of initialization of file
// static variables across translation units is not defined,
// this can lead to someone accessing the singleton before it has been
// constructed, aka undefined behavior, which is a bad thing.
//
// Thirdly, destruction is not guaranteed to occur in an order
// compatible with any references that singletons have amongst each other.
//
// namespace { const BaseType * const fileStaticVariable = Singleton::getInstance().create(); }
//
class Singleton
{
private:
static Singleton _instance;
Singleton() {}
~Singleton() {}
Singleton(const Singleton &); // intentionally undefined
Singleton & operator=(const Singleton &); // intentionally undefined
public:
static Singleton &getInstance();
};
// Source file (.cpp)
//
// Static member initialization.
//
Singleton Singleton::_instance;
Singleton &Singleton::getInstance()
{
return _instance;
}
//
// This version solves the problems of the minimalist Singleton above,
// but strictly speaking only in a single-threaded environment,
// and use in a multithreaded environment when relying on the ABI
// may still pose problems at program termination time.
//
class Singleton
{
private:
Singleton() {}
~Singleton() {}
Singleton(const Singleton &); // intentionally undefined
Singleton & operator=(const Singleton &); // intentionally undefined
public:
static Singleton &getInstance();
};
// Source file (.cpp)
Singleton& Singleton::getInstance()
{
// This local static variable is only instantiated if and when getInstance() is called.
// Although the C++ Standard (still ISO/IEC 14882:2003 as of May 2010) does not
// describe behaviour in a multithreaded environment, a commonly used C++ ABI provides
// a lock around its initialisation (check for __cxa_guard_acquire, __cxa_guard_release),
// but it is not clear how this synchronises with object destruction (are the correct
// memory fences in place?), and whether objects are correctly destroyed in reverse
// order of construction.
static Singleton instance;
return instance;
}
// Header file (.h)
//
// Attempt at an explicitly thread-safe Singleton.
// It makes fewer assumptions about the behaviour of the ABI that is not in the Standard,
// by explicitly synchronising destruction with construction
// and allowing for the possibility of improved performance through double-checked
// locking (if the ABI doesn't do that already, and assuming correct implementation),
// although it still relies on the ABI for correct relative order of destruction.
//
class Singleton
{
private:
friend class Cleanup;
class Cleanup
{
public:
~Cleanup();
}
static Singleton *_instance;
Singleton() {}
~Singleton() {}
Singleton(const Singleton &);
Singleton & operator=(const Singleton &);
public:
static Singleton &getInstance();
};
// Source file (.cpp)
//
// This is a contrived header to demonstrate the requirement of this
// code on some synchronization primitives. Replace with an appropriate
// inclusion.
#include <SyncronizationPrimitives.h>
// The use of the anonymous namespace here is to isolate / encapsulate
// thread synchronization implementation to the translation unit. This
// also has the benefit of reduced header complexity / graph in Singleton.h
namespace
{
Mutex instanceMutex;
};
Singleton* Singleton::_instance = NULL;
Singleton::Cleanup::~Cleanup()
{
// If nothing else (and it may not be clear exactly how a multi-threaded
// program shuts down, or how locking still works at this time),
// this provides proper synchronisation with thread-initiated initialisation,
// although that could also be assured by making _instance an std::atomic.
ScopedLock guard(instanceMutex);
if (_instance)
{
delete Singleton::_instance;
Singleton::_instance=NULL;
}
}
Singleton &getInstance()
{
static Cleanup _Cleanup;
#if 0 // "broken" optimisation
// You might execute the protected code only "if (!_instance)",
// and thus see a potentially substantial performance gain, but this
// "double-checked locking" technique has been proven to be unreliable,
// and in specific circumstances, depending on processor, compiler, level
// of optimisation, and program timing, such a program may misbehave.
// Then again, you might get away with it most of the time, and maybe
// your application allows to trade off reliability for performance.
// A portable way to make double-checked locking work reliably
// is to make _instance a std::atomic type (or it will be when this
// becomes part of the standard, and your programming environment
// may already provide advance support for it).
// Non-portable ways to achieve the same effect may be the use of "volatile"
// with Visual C++ 2005 or later (implying std::atomic-like behaviour
// like indivisible access and associated memory fences, which is not
// standard now and very unlikely to become so), or any other special
// provisions that sufficiently resemble std::atomic.
if (!_instance)
#else // safe but suboptimal
// To amortise the cost of obtaining the lock, the client code may
// eliminate unnecessary calls by locally storing a reference or pointer
// to the single instance it previously obtained through getInstance().
if (true)
#endif
{
// Assuming that we have some UDT that locks the mutex in its constructor
// and unlocks in the destructor.
ScopedLock guard(instanceMutex);
if (!_instance)
{
_instance = new Singleton();
}
}
return *_instance;
}
C#
/// <summary>
/// Thread-safe singleton example created at first call
/// </summary>
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
private Singleton() { }
public static Singleton Instance
{
get
{
return _instance;
}
}
}
The same example in a more concise way:
/// <summary>
/// Thread-safe singleton example created at first call
/// </summary>
public sealed class Singleton
{
public static readonly Singleton Instance = new Singleton();
}
Another method, that utilizes more of the functions of C#, could be used is as follows.
/// <summary>
/// Thread-safe singleton example created at first call
/// </summary>
public sealed class Singleton
{
/// <summary>
/// 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.
/// </summary>
public Instance { get; private set; }
/// <summary>
/// A static constructor is automatically initialized on reference
/// to the class.
/// </summary>
static Singleton() { Instance = new Singleton(); }
Singleton() { }
}
Common Lisp
In Common Lisp it is sufficient to provide a function that creates instances of classes. A hash table maps the class objects to the singleton instances. More complex solutions can be written with the Common Lisp Object System Meta-Object Protocol.
(defparameter *singleton-table* (make-hash-table))
(defun make-singleton (class &rest args)
(when (symbolp class)
(setf class (find-class class)))
(let ((instance (gethash class *singleton-table*)))
(or instance (setf (gethash class *singleton-table*)
(apply #'make-instance class args)))))
VB.NET
''' <summary>
''' Thread-safe singleton example created at first call
''' </summary>
Public NotInheritable Class Singleton
Private Shared _instance As New Singleton()
Private Sub New()
End Sub
Public Shared ReadOnly Property Instance() As Singleton
Get
Return _instance
End Get
End Property
End Class
Gambas
Gambas has a dedicated keyword, Create Static, used for automatically implementing the singleton pattern.
' Singleton.class source file ' ' The following keyword allows the class name to be used as the singleton instance. ' Note that it does not prevent the class from being instanciated otherwise. Create Static Private TheAnswer As Integer Public Sub _new() Print "The Singleton constructor" TheAnswer = 42 End Public Sub PrintTheAnswer() Print TheAnswer End
Public Sub Main() Print "I'm going to use the Singleton for the first time" Singleton.PrintTheAnswer() End
Running the previous code prints:
I'm going to use the Singleton for the first time The Singleton Constructor 42
Objective C
static Singleton *sharedSingleton = nil;
+ (Singleton*)sharedManager
{
if (sharedSingleton == nil) {
sharedSingleton = [[super allocWithZone:NULL] init];
}
return sharedSingleton;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedManager];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
Ruby
class Klass
include Singleton
end
Scala
In Scala singletons are built-in. This supports the concept that everything is an object. Since static members are not objects, that is they don't have some sort of "this" pointer, Scala adds the "object" keyword to its language. Singletons are declared just like classes except "object" replaces the keyword "class".
object MySingleton {
println("Creating the singleton")
val i : Int = 0
}
Python
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class MyClass(object):
__metaclass__ = Singleton
print MyClass()
print MyClass()
Python (using decorators)
def singleton(cls):
instance_container = []
def getinstance():
if not len(instance_container):
instance_container.append(cls())
return instance_container[0]
return getinstance
@singleton
class MyClass:
...
Note that we have to use `instance_container` instead of a simple variable because otherwise we would have to assign this variable directly in the inner function which would make it local to the inner function. See PEP-3104 for more extensive explanation. Note python 2.6+
PHP
class Singleton
{
private static $_instance;
public static function getInstance()
{
if (!(self::$_instance instanceof self))
{
self::$_instance = new self();
}
return self::$_instance;
}
// Do not allow an explicit call of the constructor: $v = new Singleton();
final private function __construct() { }
// Do not allow the clone operation: $x = clone $v;
final private function __clone() { }
}
$instance = Singleton::getInstance();
Flash ActionScript
public class Singleton
{
private static var _instance:Singleton = new Singleton();
public function Singleton()
{
if (_instance) throw new Error ("use getInstance() method!");
}
public static function getInstance():Singleton
{
return _instance;
}
}
Javascript
These examples use Firebug console to output information.
Implementation 1
Singletons are native and conveniently implemented in Javascript. Singleton in Javascript is implemented as: object literal {}
.
var Singleton1 = {
name: 'Singleton1'
};
var s1i1 = Singleton1;
var s1i2 = Singleton1;
s1i2.name = 'singleton1 instance2';
console.log(s1i1.name); // outputs 'singleton1 instance2'
Implementation 2
This is classical approach to the singleton pattern in Javascript. This is self-executing function in Javascript. It returns(to var Singleton2
)
object with accessor to Singleton instance and some other variables and methods, basically like static variables and methods in other languages.
var Singleton2 = (function () {
/**
* Singleton object constructor.
*
* @param object args Arguments for the singleton object
*/
function Singleton(args) {
var args = args || {};
this.name = 'Singleton2';
this.x = args.x || 10; // get x from arguments or set default
}
// instance holder
var instance;
// Emulated static variables and methods
var _static = {
name: 'Singleton2',
/**
* Instance accessor. Method for getting instance.
*
* @param object args Arguments for the singleton object
*
* @return Singleton instance of Singleton object
*/
getInstance: function (args) {
if (instance === undefined) {
instance = new Singleton(args);
}
return instance;
}
};
return _static;
})();
var s2i1 = Singleton2.getInstance({x: 100});
var s2i2 = Singleton2.getInstance();
s2i2.x = 20;
console.log(s2i1.x); // outputs '20'
Performance
Testing performance between native and classical implementation. Store 1000000 instances of singleton in array.
// Singleton1
var s1s = [];
console.time('s1');
for (var i = 1; i <= 1000000; i++) {
s1s[i] = Singleton1;
}
console.timeEnd('s1');
// Result: depending on browser - ~75-85ms
// Singleton2
var s2s = [];
console.time('s2');
for (var i = 1; i <= 1000000; i++) {
s2s[i] = Singleton2.getInstance({x:i});
}
console.timeEnd('s2');
// Result: depending on browser - ~160-1500ms
Conclusion
Implementation 1 (native Javascript way) - good performance and simple to implement.
Implementation 2 (classical way) - bad performance and complex to implement.
MATLAB
The Singleton Pattern in object-oriented MATLAB is demonstrated in MATLAB Central File Exchange item Design Pattern: Singleton (Creational). This implementation is written in the new class-definition syntax introduced with MATLAB software version 7.6 (R2008a)
[9]
and uses a persistent
variable to store the singleton instance within the scope of a static accessor method. Further, it conforms to the initialization on demand holder idiom as discussed in The solution of Bill Pugh.
Delphi
This Delphi implementation of the a singleton class also has garbage collecting built into it. Note that it uses a shared destructor which is only supported in Delphi 2010 and newer versions.
// Class declaration in interface section
type
TSingleton = class
private
class var FInstance: TSingleton;
class destructor Destroy;
class function GetInstance: TSingleton; static;
public
class property Instance: TSingleton read GetInstance;
end;
// Class code in implementation section
class destructor TSingleton.Destroy;
begin
if Assigned(FInstance) then
FInstance.Free;
end;
class function TSingleton.GetInstance: TSingleton;
begin
if not Assigned(FInstance) then
FInstance := TSingleton.Create;
Result := FInstance;
end;
Prototype-based singleton
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. Example in Io:
Foo := Object clone Foo clone := Foo
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
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.[10]
References
- ^ Alex Miller. Patterns I hate #1: Singleton, July 2007
- ^ Scott Densmore. Why singletons are evil, May 2004
- ^ Steve Yegge. Singletons considered stupid, September 2004
- ^ J.B. Rainsberger, IBM. Use your singletons wisely, July 2001
- ^ Chris Reath. Singleton I love you, but you're bringing me down, October 2008
- ^ a b http://googletesting.blogspot.com/2008/11/clean-code-talks-global-state-and.html
- ^ Gamma, E, Helm, R, Johnson, R, Vlissides, J: "Design Patterns", page 128. Addison-Wesley, 1995
- ^ Pugh, Bill (November 16, 2008). "The Java Memory Model". Retrieved April 27, 2009.
- ^ "New Class-Definition Syntax Introduced with MATLAB Software Version 7.6". The MathWorks, Inc. March 2009. Retrieved August 6, 2009.
- ^ Yohan Liyanage Breaking the Singleton, September 21, 2009
- "C++ and the Perils of Double-Checked Locking" Meyers, Scott and Alexandrescu, Andrei, September 2004.
- "The Boost.Threads Library" Kempf, B., Dr. Dobb's Portal, April 2003.
External links
![]() | This article's use of external links may not follow Wikipedia's policies or guidelines. (September 2009) |
- How to make a class singleton
- The "Double-Checked Locking is Broken" Declaration (Java)
- A Pattern Enforcing Compiler that enforces the Singleton pattern amongst other patterns
- Description from the Portland Pattern Repository
- Implementing the Singleton Pattern in C# by Jon Skeet
- A Threadsafe C++ Template Singleton Pattern for Windows Platforms by O. Patrick Barnes
- Implementing the Inheritable Singleton Pattern in PHP5
- Singleton Pattern and Thread Safety
- PHP patterns
- Design Patterns for Web Programming in PHP
- Javascript implementation of a Singleton Pattern by Christian Schaefer
- Singletons Cause Cancer by Preston Lee
- Singleton examples
- Article "Double-checked locking and the Singleton pattern" by Peter Haggar
- Article "Use your singletons wisely" by J. B. Rainsberger
- Article "Simply Singleton" by David Geary
- Article "Description of Singleton" by Aruna
- Article "Why Singletons Are Controversial"
- The Google Singleton Detector analyzes Java bytecode to detect singletons, so that their usefulness can be evaluated.
- Serialization of Singleton in Java
- Breaking the Singleton Pattern using Reflection in Java
- Singleton at Microsoft patterns & practices Developer Center
- Singleton Class in ActionScript 3
- Standard way of implementing Singletons in ActionScript 3
- singleton: Ruby Standard Library Documentation
- Polymorphic_Singletons C++