Singleton pattern
Encyclopedia
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.
There is criticism to the use of the singleton pattern, as some consider it an anti-pattern
, judging that it is overused, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application.
In C++ it also serves to isolate from the unpredictability of the order of dynamic initialization, returning control to the programmer.
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 private. 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.
solutions provided here are all thread-safe
but differ in supported language versions and lazy-loading
. Since Java 5.0, the easiest way to create a Singleton is the enum type approach, given at the end of this section.
without requiring special language constructs, but it may lack the laziness of the one above. 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:
Computer Science researcher Bill Pugh
has written about the code issues underlying the Singleton pattern when implemented in Java. 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.
Alternatively, the inner class Singletonholder can be also substituted by implementing a Property which provides also access to the static final/readonly class members. Just like the lazy object in C#, whenever the Singleton.Instance Property is called, this singleton is instantiated for the very first time.
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.
This approach does provide a mechanism for global access when preventing from instantiating a class instance at all. Enum can be replaced with a construct, a static class field. Nonetheless, it doesn't provide a way when willing to instantiate an object in whatsoever manner when needed, for instance, lazy initialization. In other words, it doesn't offer a trigger manner like Singleton instance or Lazy Value.
Prototype-based 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).
is an abstract class that binds
the various AWT components to particular native toolkit implementations. The
subclass of
The binding performed by the toolkit allows, for example, the backing implementation of a to bind to the platform-specific
Drawbacks
This pattern makes unit testing far more difficult, 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, e.g., 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 or PHP.
External links
Software engineering
Software Engineering is the application of a systematic, disciplined, quantifiable approach to the development, operation, and maintenance of software, and the study of these approaches; that is, the application of engineering to software...
, the singleton pattern is a design pattern
Design pattern (computer science)
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that...
used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
. 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.
There is criticism to the use of the singleton pattern, as some consider it an anti-pattern
Anti-pattern
In software engineering, an anti-pattern is a pattern that may be commonly used but is ineffective and/or counterproductive in practice.The term was coined in 1995 by Andrew Koenig,...
, judging that it is overused, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application.
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 FactoryAbstract factory patternThe abstract factory pattern is a software design pattern that provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the...
, BuilderBuilder patternThe builder pattern is an object creation software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects...
, and PrototypePrototype patternThe prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects...
patterns can use Singletons in their implementation. - FacadeFaçade patternThe facade pattern is a software engineering design pattern commonly used with Object-oriented programming. The name is by analogy to an architectural facade....
Objects are often Singletons because only one Facade object is required. - State objectsState patternThe state pattern, which closely resembles Strategy Pattern, is a behavioral software design pattern, also known as the objects for states pattern. This pattern is used in computer programming to represent the state of an object. This is a clean way for an object to partially change its type at...
are often Singletons. - Singletons are often preferred to global variables because:
- They don't pollute the global name space (or, in languages with namespaces, their containing namespace) with unnecessary variables.
- They permit lazyLazy evaluationIn programming language theory, lazy evaluation or call-by-need is an evaluation strategy which delays the evaluation of an expression until the value of this is actually required and which also avoids repeated evaluations...
allocation and initialization, whereas global variables in many languages will always consume resources.
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 classClass (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
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
Constructor (computer science)
In object-oriented programming, a constructor in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created...
is made private. 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
Interface (computer science)
In the field of computer science, an interface is a tool and concept that refers to a point of interaction between components, and is applicable at the level of both hardware and software...
, 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
Thread (computer science)
In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process...
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
Mutual exclusion
Mutual exclusion algorithms are used in concurrent programming to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code called critical sections. A critical section is a piece of code in which a process or thread accesses a common resource...
on the class that indicates that the object is being instantiated.
Example
The Java programming languageJava (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
solutions provided here are all thread-safe
Thread-safe
Thread safety is a computer programming concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it only manipulates shared data structures in a thread-safe manner, which enables safe execution by multiple threads at the same time...
but differ in supported language versions and lazy-loading
Lazy initialization
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed....
. Since Java 5.0, the easiest way to create a Singleton is the enum type approach, given at the end of this section.
Lazy initialization
Traditional simple way
This solution is thread-safeThread-safe
Thread safety is a computer programming concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it only manipulates shared data structures in a thread-safe manner, which enables safe execution by multiple threads at the same time...
without requiring special language constructs, but it may lack the laziness of the one above. 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:
The solution of Bill Pugh
University of MarylandUniversity of Maryland, College Park
The University of Maryland, College Park is a top-ranked public research university located in the city of College Park in Prince George's County, Maryland, just outside Washington, D.C...
Computer Science researcher Bill Pugh
William Pugh
William Pugh is the inventor of the skip list, the Omega test for deciding Presburger arithmetic, co-author of the static code analysis tool FindBugs, and was highly influential in the development of the current memory model of the Java language together with his PhD student Jeremy Manson.He is...
has written about the code issues underlying the Singleton pattern when implemented in Java. Pugh's efforts on the "Double-checked locking
Double-checked locking
In software engineering, double-checked locking is a software design pattern used to reduce the overhead of acquiring a lock by first testing the locking criterion without actually acquiring the lock...
" 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
Initialization on demand holder idiom
In software engineering, the Initialization on Demand Holder idiom is a lazy-loaded singleton. The idiom can be implemented in both single-threaded/serial and concurrent environments, but care must be taken to correctly implement the idiom under concurrent conditions.- Example Java Implementation...
, 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
).Alternatively, the inner class Singletonholder can be also substituted by implementing a Property which provides also access to the static final/readonly class members. Just like the lazy object in C#, whenever the Singleton.Instance Property is called, this singleton is instantiated for the very first time.
The Enum way
In the second edition of his book "Effective Java" Joshua BlochJoshua Bloch
Joshua J. Bloch is a software engineer, currently employed at Google, and a technology author. He led the design and implementation of numerous Java platform features, including the Java Collections Framework, the java.math package, and the assert mechanism...
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.
This approach does provide a mechanism for global access when preventing from instantiating a class instance at all. Enum can be replaced with a construct, a static class field. Nonetheless, it doesn't provide a way when willing to instantiate an object in whatsoever manner when needed, for instance, lazy initialization. In other words, it doesn't offer a trigger manner like Singleton instance or Lazy Value.
Prototype-based singleton
In a prototype-based programmingPrototype-based programmingPrototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-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 IoIo (programming language)Io is a pure object-oriented programming language inspired by Smalltalk, Self, Lua, Lisp, Act1, and NewtonScript. Io has a prototype-based object model similar to the ones in Self and NewtonScript, eliminating the distinction between instance and class. Like Smalltalk, everything is an object and...
:
Foo := Object clone
Foo clone := Foo
Example of use with the factory method patternThe singleton pattern is often used in conjunction with the factory method pattern
Factory method pattern
The factory method pattern is an object-oriented design pattern to implement the concept of factories. Like other creational patterns, it deals with the problem of creating objects without specifying the exact class of object that will be created.The creation of an object often requires complex...
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
Abstract Window Toolkit
The Abstract Window Toolkit is Java's original platform-independent windowing, graphics, and user-interface widget toolkit. The AWT is now part of the Java Foundation Classes — the standard API for providing a graphical user interface for a Java program.AWT is also the GUI toolkit for a...
(AWT).
is an abstract class that binds
Name binding
In programming languages, name binding is the association of objects with identifiers. An identifier bound to an object is said to reference that object. Machine languages have no built-in notion of identifiers, but name-object bindings as a service and notation for the programmer is implemented...
the various AWT components to particular native toolkit implementations. The
Toolkit
class has a factory method that returns the platform-specificPlatform-specific model
A platform-specific model is a model of a software or business system that is linked to a specific technological platform . Platform-specific models are indispensable for the actual implementation of a system.For example, a need to implement an online shop...
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 .The binding performed by the toolkit allows, for example, the backing implementation of a 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, 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, e.g., by locking.
Advocates of dependency injection
Dependency injection
Dependency injection is a design pattern in object-oriented computer programming whose purpose is to improve testability of, and simplify deployment of components in very large software systems....
would regard this as an anti-pattern
Anti-pattern
In software engineering, an anti-pattern is a pattern that may be commonly used but is ineffective and/or counterproductive in practice.The term was coined in 1995 by Andrew Koenig,...
, 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
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime....
in languages such as Java or PHP.
External links
- Book extract: Implementing the Singleton Pattern in C# by Jon Skeet
- Singleton at Microsoft patterns & practices Developer Center
- PHP documentation for Singleton
- Ruby standard library documentation for Singleton
- IBM article "Double-checked locking and the Singleton pattern" by Peter Haggar
- IBM article "Use your singletons wisely" by J. B. RainsbergerJ. B. RainsbergerJ. B. Rainsberger is a Canadian software development consultant and technology writer, best known for his contributions to agile development, for which he was awarded the highest honor from the agile community, the Gordon Pask Award in 2005 . He is the founder of...
- Javaworld article " Simply Singleton" by David Geary
- Google article "Why Singletons Are Controversial"
- Google Singleton Detector (analyzes Java bytecodeJava bytecodeJava bytecode is the form of instructions that the Java virtual machine executes. Each bytecode opcode is one byte in length, although some require parameters, resulting in some multi-byte instructions. Not all of the possible 256 opcodes are used. 51 are reserved for future use...
to detect singletons)