Singleton Pattern
   HOME

TheInfoList



OR:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differentl ...
to a singular instance. One of the well-known "Gang of Four" design patterns, which describes how to solve recurring problems in object-oriented software, the pattern is useful when exactly one object is needed to coordinate actions across a system. More specifically, the singleton pattern allows objects to: * Ensure they only have one instance * Provide easy access to that instance * Control their instantiation (for example, hiding the constructors of a
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differentl ...
) The term comes from the mathematical concept of a singleton.


Common uses

Singletons are often preferred to
global variables In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the ''global environment'' or ''global s ...
because they do not pollute the global namespace (or their containing namespace). Additionally, they permit lazy allocation and initialization, whereas global variables in many languages will always consume resources. The singleton pattern can also be used as a basis for other design patterns, such as the
abstract factory The abstract factory pattern provides a way to encapsulate a group of individual factory object, factories that have a common theme without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of ...
,
factory method In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by cr ...
,
builder Builder may refer to: * Construction worker, who specializes in building work * Carpenter, a skilled craftsman who works with wood * General contractor, that specializes in building work ** Subcontractor * Builder (detergent), a component of moder ...
and
prototype A prototype is an early sample, model, or release of a product built to test a concept or process. It is a term used in a variety of contexts, including semantics, design, electronics, and Software prototyping, software programming. A prototyp ...
patterns. Facade objects are also often singletons because only one facade object is required.
Logging Logging is the process of cutting, processing, and moving trees to a location for transport. It may include skidding, on-site processing, and loading of trees or logs onto trucks or skeleton cars. Logging is the beginning of a supply chain ...
is a common real-world use case for singletons, because all objects that wish to log messages require a uniform point of access and conceptually write to a single source.


Implementations

Implementations of the singleton pattern ensure that only one instance of the singleton class ever exists and typically provide
global access Global means of or referring to a globe and may also refer to: Entertainment * ''Global'' (Paul van Dyk album), 2003 * ''Global'' (Bunji Garlin album), 2007 * ''Global'' (Humanoid album), 1989 * ''Global'' (Todd Rundgren album), 2015 * Bruno ...
to that instance. Typically, this is accomplished by: * Declaring all constructors of the class to be
private Private or privates may refer to: Music * " In Private", by Dusty Springfield from the 1990 album ''Reputation'' * Private (band), a Denmark-based band * "Private" (Ryōko Hirosue song), from the 1999 album ''Private'', written and also recorde ...
, which prevents it from being instantiated by other objects * Providing a static method that returns a reference to the instance The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before when the static method is first called. This C++11 implementation is based on the pre C++98 implementation in the book . #include class Singleton ; Singleton* Singleton::instance = nullptr; // definition class variable int main() The program output is value=42 This is an implementation of the Meyers singleton in C++11. The Meyers singleton has no destruct method. The program output is the same as above. #include class Singleton ; int main()


Lazy initialization

A singleton implementation may use lazy initialization in which the instance is created when the static method is first invoked. In multithreaded programs, this can cause race conditions that result in the creation of multiple instances. The following Java 5+ example is a thread-safe implementation, using lazy initialization with
double-checked locking In software engineering, double-checked locking (also known as "double-checked locking optimization") is a software design pattern used to reduce the overhead of acquiring a lock by testing the locking criterion (the "lock hint") before acquiring th ...
. public class Singleton


Criticism

Some consider the singleton to be an anti-pattern that introduces global state into an application, often unnecessarily. This introduces a potential dependency on the singleton by other objects, requiring analysis of implementation details to determine whether a dependency actually exists. This increased coupling can introduce difficulties with unit testing. In turn, this places restrictions on any abstraction that uses the singleton, such as preventing concurrent use of multiple instances.Steve Yegge
Singletons considered stupid
September 2004
Hevery, Miško,

, ''Clean Code Talks'', 21 November 2008.
Singletons also violate the single-responsibility principle because they are responsible for enforcing their own uniqueness along with performing their normal functions.


See also

*
Initialization-on-demand holder idiom In software engineering, the initialization-on-demand holder (design pattern) idiom is a lazy-loaded singleton. In all versions of Java, the idiom enables a safe, highly concurrent lazy initialization of static fields with good performance. publi ...
*
Multiton pattern In software engineering, the multiton pattern is a design pattern which generalizes the singleton pattern. Whereas the singleton allows only one instance of a class to be created, the multiton pattern allows for the controlled creation of multip ...
* Software design pattern


References


External links

* Complete article
Java Singleton Pattern Explained
* Four different ways to implement singleton in Java
Ways to implement singleton in Java
* Book extract
Implementing the Singleton Pattern in C#
by Jon Skeet
Singleton at Microsoft patterns & practices Developer Center
* IBM article
Double-checked locking and the Singleton pattern
by Peter Haggar *
Google Singleton Detector
(analyzes Java bytecode to detect singletons) {{DEFAULTSORT:Singleton Pattern Software design patterns Anti-patterns Articles with example Java code