In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. (This concept is also sometimes generalized to restrict the instance to a specific number of objects - for example, we can restrict the number of instances to five objects.) 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 by some people, who feel that it is overly used, introducing unnecessary limitations in situations where a sole instance of a class is not actually required.
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:
They don't pollute the global namespace (or, in languages with namespaces, their containing namespace) with unnecessary variables.
They permit lazy allocation and initialization, where global variables in many languages will always consume resources.
Singletons behave differently depending on the lifetime of the virtual machine. While a software development kit may start a new virtual machine for every run which results in a new instance of the singleton being created, calls to a singleton e.g. within the virtual machine of an application server behave differently. There the virtual machine remains alive, therefore the instance of the singleton remains as well. Running the code again therefore can retrieve the "old" instance of the singleton which then may be contaminated with values in local fields which are the result of the first run.
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.
The Scala programming language supports Singleton objects out-of-the-box. The 'object' keyword creates a class and also defines a singleton object of that type. As the concept is implemented natively, the design pattern to implement the concept is not required in this language.
This is the recommended method. It is known as the initialization on demand holder idiom and is as lazy as possible. Moreover, it works in all known versions of Java. This solution is the most portable across different Java compilers and virtual machines.
The inner 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 and/or synchronized).
Traditional simple way
Just like the one above, this solution is thread-safe without requiring special language constructs, but it lacks the laziness. The INSTANCE is created as soon as the Singleton class loads. 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, this (slightly) simpler solution can be used:
Sometimes the static final field is made private and a static factory-method is provided to get the instance. This way the underlying implementation may change easily while it has no more performance-issues on modern JVMs.
Java 5 solution
If and only if the compiler used is Java 5 (also known as Java 1.5) or newer, AND all Java virtual machines the application is going to run on fully support the Java 5 memory model, then (and only then) the volatile double checked locking can be used (for a detailed discussion of why it should never be done before Java 5 see The "Double-Checked Locking is Broken" Declaration):
Allen Holub (in "Taming Java Threads", Berkeley, CA: Apress, 2000, pp. 176–178) notes that on multi-CPU systems (which are widespread as of 2007), the use of volatile may have an impact on performance approaching to that of synchronization, and raises the possibility of other problems. Thus this solution has little to recommend it over Pugh's solution described above.
In the second edition of his book "Effective Java" Joshua Bloch claims that "a single-element enum type is the best way to implement a singleton for any Java that supports enums. The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.
Singleton pattern in PHP 5:
Private constructors are not available in ActionScript 3.0 - which prevents the use of the ActionScript 2.0 approach to the Singleton Pattern. Many different AS3 Singleton implementations have been published around the web.
A common way to implement a singleton in Objective-C is the following:
If thread-safety is not required, the synchronization can be left out, leaving the +sharedSingleton method like this:
This pattern is widely used in the Cocoa frameworks (see for instance, NSApplication, NSColorPanel, NSFontPanel or NSWorkspace, to name but a few).
Some may argue that this is not, strictly speaking, a Singleton, because it is possible to allocate more than one instance of the object. A common way around this is to use assertions or exceptions to prevent this double allocation.
There are alternative ways to express the Singleton pattern in Objective-C, but they are not always as simple or as easily understood, not least because they may rely on the -init method returning an object other than self. Some of the Cocoa "Class Clusters" (e.g. NSString, NSNumber) are known to exhibit this type of behaviour.
Note that @synchronized is not available in some Objective-C configurations, as it relies on the NeXT/Apple runtime. It is also comparatively slow, because it has to look up the lock based on the object in parentheses. Check the history of this page for a different implementation using an NSConditionLock.
C++ (using pthreads)
This is an example of an almost correct (see note at the bottom of C++(using pthreads)), eager initialized, thread-safe singleton implementation in C++.
This implementation depends upon the guarantee that namespace scope variables are constructed in a thread-safe and single threaded way. This is generally true. However, if someone in the process create threads before main, or if you create threads inside a dynamically loaded library while it's being loaded, then we can no longer guarantee that the initialization happens in a single threaded environment. We would then be unable to guarantee thread-safe single initialization.
Notice how the pointer to the singleton is a static local of the function and not a global or a static member of the class. This is because of the static initialization order fiasco ; there is no specified order of construction of namespace scope variables between translation units. The pointer is a static local of the function to avoid this lack of defined construction order.
Also note that we never destroy the Singleton instance. The problem is if we destroy it, another static storage object may refer to our singleton after it's been destroyed in its destructor, probably causing bad things to happen. This problem is known as the static deinitialization order fiasco. If the Singleton is only memory, leaking the singleton is ok. The operating system will reclaim all of the process's memory anyway when the process dies. However, if the singleton has other non-memory resources which the operating system will not reclaim when the process dies, then you would want to destroy your singleton before the process exits, but you would have to be careful to ensure the proper order of destruction.
By using a mutex in the singleton's initialization, we may perform lazy initialization in a thread-safe way. The following sample demonstrates correct usage with the pthreads threading library.
It also demonstrates the broken double-checked locking anti-pattern with commented code. A common broken "pattern" for thread safety with the singleton pattern is to use double-checked locking. However, due to the absence of any consideration being given to multiple threads of execution in the language standard, the ability of modern processors to re-order instructions (as long as the result is consistent with their architecturally-specified memory model), and the cache coherency problem of multi-core processors, double-checked locking is intrinsically prone to failure in C++. There is no model — other than runtime libraries (e.g. POSIX threads, designed to provide concurrency primitives) — that can provide the necessary execution order.
This is an almost correct (see note at the bottom of C++(using pthreads)), lazy initialized, thread safe singleton example.
Notice that we did not create the mutex as a static local in the function. This would lead to not thread-safe initialization of the mutex, the very thing we're trying to solve with the mutex! Nor can we make it a static class member or a namespace member because of the static initialization order fiasco. The only alternative is to make the mutex it's own eager initialized singleton.
Note the use of the MutexGuard class in the Singleton::instance() function. The MutexGuard is being used as an RAII object, also known as scoped lock, guaranteeing that the Mutex's lock will be relinquished even if an exception is thrown during the memory allocation or Singleton's constructor as the language specification pledges that the destructors of stack objects are invoked during stack unwinding.
This implementation acquires the Mutex's lock on every call to Singleton::instance(), even though the Mutex is only needed for the first few calls to guarantee a single initialization and to guarantee that the single initialization is visible to all calling threads.
One option to avoid this extra overhead is to use the eager initialized version.
Another option is to use thread local storage to better implement the instance() method.
Alternatively, one could use pthread_once to guarantee single initialization.
However, it's preferable to not try to lessen the overhead by having users cache the pointer. Having users cache the return of instance() is begging for the static deinitialization order fiasco. For this very reason, try to phrase your singletons as a list of namespace functions instead of as a class. The namespace functions will still be implemented in terms of your singleton class, but it will be impossible for the user to cache a pointer to your singleton and accidentally access it after it's been destroyed. (You would still have to clearly document that your interface is implemented with a static storage object to allow users to force the correct order of destruction.)
More code must be written if the singleton code is located in a static shared library as each library statically linked against the static library will have their own copy of the singleton. If several dynamically loaded libraries are created by statically linking against the static shared library with the singleton, each dynamically linked library will have their own copy of the singleton. An executable might load several of these dynamically linked libraries at the same time, resulting in a process with multiple copies of the singleton. To avoid that, the singleton code must be inside the executable itself or inside a dynamically linked library. Alternatively, the singleton can be rewritten to use a memory-mapped file to store the singleton instance.
Finally, both of these examples are not technically safe and correct. The C++ standard allows the dynamic initialization of namespace scope variables to be delayed until the first use of the translation unit. Thus we are unable to guarantee that the eager initialization will occur before main is called (or the DLL is loaded), and thus before there are threads. Most compilers do not delay the initialization, but it's possible a compiler could. Thus the only remaining safe and platform independent way is to use pthread_once to guarantee a single, thread-safe initialization of a singleton.
Another example(using static constructor)
Example in C# 2.0 (thread-safe with lazy initialization)
Note: This is not a recommended implementation because "TestClass" has a default public constructor, and that violates the definition of a Singleton. A proper Singleton must never be instantiable more than once.
According to influential Python programmer Alex Martelli, The Singleton design pattern (DP) has a catchy name, but the wrong focus—on identity rather than on state. The Borg design pattern has all instances share state instead. A rough consensus in the Python community is that sharing state among instances is more elegant, at least in Python, than is caching creation of identical instances on class initialization. Coding shared state is nearly transparent:
But with the new style class, this is a better solution, because only one instance is created:
get_Instance returning value(Result) type ref to lcl_Singleton.
fg_Singleton type ref to lcl_Singleton.
class lcl_Singleton implementation.
if (fg_Singleton is initial ).
create object fg_Singleton.
Result = fg_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 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-specificsubclass 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 .
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.