Singleton Pattern
   HOME

TheInfoList



OR:

In
software engineering Software engineering is a systematic engineering approach to software development. A software engineer is a person who applies the principles of software engineering to design, develop, maintain, test, and evaluate computer software. The term '' ...
, the singleton pattern is a
software design pattern In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code ...
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 describe 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 In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified. Namespaces ...
(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,
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 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 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 A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any of ...
that returns a
reference Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''name'' ...
to the instance The instance is usually stored as a private
static variable In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
; the instance is created when the variable is initialized, at some point before when the static method is first called. The following demonstrates an example implementation in
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
: public class Coin


Lazy initialization

A singleton implementation may use
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. It is a kind of lazy evaluation that refers specificall ...
in which the instance is created when the static method is first invoked. In multithreaded programs, this can cause
race conditions A race condition or race hazard is the condition of an electronics, software, or other system where the system's substantive behavior is dependent on the sequence or timing of other uncontrollable events. It becomes a bug when one or more of ...
that result in the creation of multiple instances. The following Java example is a
thread-safe Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without uni ...
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 An anti-pattern in software engineering, project management, and business processes is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive. The term, coined in 1995 by computer programmer An ...
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 A coupling is a device used to connect two shafts together at their ends for the purpose of transmitting power. The primary purpose of couplings is to join two pieces of rotating equipment while permitting some degree of misalignment or end mov ...
can introduce difficulties with
unit testing In computer programming, unit testing is a software testing method by which individual units of source code—sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures&md ...
. In turn, this places restrictions on any abstraction that uses the singleton, such as preventing
concurrent Concurrent means happening at the same time. Concurrency, concurrent, or concurrence may refer to: Law * Concurrence, in jurisprudence, the need to prove both ''actus reus'' and ''mens rea'' * Concurring opinion (also called a "concurrence"), a ...
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 The single-responsibility principle (SRP) is a computer programming principle that states that "A module should be responsible to one, and only one, actor." The term actor refers to a group (consisting of one or more stakeholders or users) that ...
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 In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code ...


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 In computing, Java bytecode is the bytecode-structured instruction set of the Java virtual machine (JVM), a virtual machine that enables a computer to run programs written in the Java programming language and several other programming langua ...
to detect singletons) {{DEFAULTSORT:Singleton Pattern Software design patterns Anti-patterns Articles with example Java code