HOME

TheInfoList



OR:

In
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
, the singleton pattern is a
software design pattern In software engineering, a software design pattern or design pattern is a general, reusable solution to a commonly occurring problem in many contexts in software design. A design pattern is not a rigid structure to be transplanted directly into s ...
that restricts the instantiation of a
class Class, Classes, 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 d ...
to a singular instance. It is 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 classes 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, Classes, 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 d ...
) The term comes from the mathematical concept of a singleton.


Common uses

Singletons are often preferred to global variables 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 The abstract factory pattern in software engineering is a design pattern that provides a way to create families of related objects without imposing their concrete classes, by encapsulating a group of individual factories that have a common theme w ...
, factory method, 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 prototype ...
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 skidder, skidding, on-site processing, and loading of trees or trunk (botany), logs onto logging truck, trucks


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 recorded ...
, 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 an object, and generally also a message. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be us ...
that returns a
reference A 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 ''nam ...
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. This
C++23 C++23, formally ISO/IEC 14882:2024, is the current open standard for the C++ programming language that follows C++20. The final draft of this version is N4950. In February 2020, at the final meeting for C++20 in Prague, an overall plan for C++ ...
implementation is based on the pre-C++98 implementation in the book . import std; 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. import std; 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 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, leading to unexpected or inconsistent ...
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. 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 can introduce difficulties with
unit testing Unit testing, component or module testing, is a form of software testing by which isolated source code is tested to validate expected behavior. Unit testing describes tests that are run at the unit-level to contrast testing at the Integration ...
. 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 * Multiton pattern *
Software design pattern In software engineering, a software design pattern or design pattern is a general, reusable solution to a commonly occurring problem in many contexts in software design. A design pattern is not a rigid structure to be transplanted directly into s ...


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 Java bytecode is the instruction set of the Java virtual machine (JVM), the language to which Java and other JVM-compatible source code is compiled. Each instruction is represented by a single byte, hence the name bytecode, making it a compact ...
to detect singletons) {{DEFAULTSORT:Singleton Pattern Software design patterns Anti-patterns Articles with example Java code