Menu
Home Explore People Places Arts History Plants & Animals Science Life & Culture Technology
On this page
Singleton pattern
Design pattern in object-oriented software development

In object-oriented programming, the singleton pattern is a design approach that restricts the instantiation of a class to a single instance. It is one of the famous "Gang of Four" design patterns, used to solve common software problems by ensuring only one object coordinates actions across a system. The pattern controls instantiation, often by hiding constructors, and provides easy access to the sole instance. Its name is derived from the mathematical concept of a singleton.

Related Image Collections Add Image
We don't have any YouTube videos related to Singleton pattern yet.
We don't have any PDF documents related to Singleton pattern yet.
We don't have any Books related to Singleton pattern yet.
We don't have any archived web articles related to Singleton pattern yet.

Common uses

Singletons are often preferred to global variables 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.34

The singleton pattern can also be used as a basis for other design patterns, such as the abstract factory, factory method, builder and prototype patterns. Facade objects are also often singletons because only one facade object is required.

Logging 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.5

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:

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++23 implementation is based on the pre-C++98 implementation in the book .

import std; class Singleton { public: // defines an class operation that lets clients access its unique instance. static Singleton& get() { // may be responsible for creating its own unique instance. if (nullptr == instance) instance = new Singleton; return *instance; } Singleton(const Singleton&) = delete; // rule of three Singleton& operator=(const Singleton&) = delete; static void destruct() { delete instance; instance = nullptr; } // existing interface goes here int getValue() { return value; } void setValue(int value_) { value = value_; } private: Singleton() = default; // no public constructor ~Singleton() = default; // no public destructor static Singleton* instance; // declaration class variable int value; }; Singleton* Singleton::instance = nullptr; // definition class variable int main() { Singleton::get().setValue(42); std::println("value={}", Singleton::get().getValue()); Singleton::destruct(); }

The program output is

value=42

This is an implementation of the Meyers singleton6 in C++11. The Meyers singleton has no destruct method. The program output is the same as above.

import std; class Singleton { public: static Singleton& get() { static Singleton instance; return instance; } int getValue() { return value; } void setValue(int value_) { value = value_; } private: Singleton() = default; ~Singleton() = default; int value; }; int main() { Singleton::get().setValue(42); std::println("value={}", Singleton::get().getValue()); }

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+ example7 is a thread-safe implementation, using lazy initialization with double-checked locking.

public class Singleton { private static volatile Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }

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.8 This increased coupling can introduce difficulties with unit testing.9 In turn, this places restrictions on any abstraction that uses the singleton, such as preventing concurrent use of multiple instances.101112

Singletons also violate the single-responsibility principle because they are responsible for enforcing their own uniqueness along with performing their normal functions.13

See also

The Wikibook Computer Science/Design Patterns has a page on the topic of: Singleton implementations in various languages Wikimedia Commons has media related to Singleton pattern.

References

  1. Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 127ff. ISBN 0-201-63361-2.{{cite book}}: CS1 maint: multiple names: authors list (link) 0-201-63361-2

  2. "The Singleton design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-16. http://w3sdesign.com/?gr=c05&ugr=proble

  3. Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 127ff. ISBN 0-201-63361-2.{{cite book}}: CS1 maint: multiple names: authors list (link) 0-201-63361-2

  4. Soni, Devin (31 July 2019). "What Is a Singleton?". BetterProgramming. Retrieved 28 August 2021. https://betterprogramming.pub/what-is-a-singleton-2dc38ca08e92

  5. Rainsberger, J.B. (1 July 2001). "Use your singletons wisely". IBM. Archived from the original on 24 February 2021. Retrieved 28 August 2021. https://web.archive.org/web/20210224180356/https://www.ibm.com/developerworks/library/co-single/

  6. Scott Meyers (1997). More Effective C++. Addison Wesley. pp. 146 ff. ISBN 0-201-63371-X. 0-201-63371-X

  7. Eric Freeman, Elisabeth Freeman, Kathy Sierra, and Bert Bates (October 2004). "5: One of a Kind Objects: The Singleton Pattern". Head First Design Patterns (First ed.). O'Reilly Media, Inc. p. 182. ISBN 978-0-596-00712-6.{{cite book}}: CS1 maint: multiple names: authors list (link) 978-0-596-00712-6

  8. "Why Singletons Are Controversial". Google Code Archive. Archived from the original on 6 May 2021. Retrieved 28 August 2021. https://web.archive.org/web/20210506162753/https://code.google.com/archive/p/google-singleton-detector/wikis/WhySingletonsAreControversial.wiki

  9. Button, Brian (25 May 2004). "Why Singletons are Evil". Being Scott Densmore. Microsoft. Archived from the original on 15 July 2021. Retrieved 28 August 2021. https://web.archive.org/web/20210715184717/https://docs.microsoft.com/en-us/archive/blogs/scottdensmore/why-singletons-are-evil

  10. Button, Brian (25 May 2004). "Why Singletons are Evil". Being Scott Densmore. Microsoft. Archived from the original on 15 July 2021. Retrieved 28 August 2021. https://web.archive.org/web/20210715184717/https://docs.microsoft.com/en-us/archive/blogs/scottdensmore/why-singletons-are-evil

  11. Steve Yegge. Singletons considered stupid, September 2004 http://steve.yegge.googlepages.com/singleton-considered-stupid

  12. Hevery, Miško, "Global State and Singletons", Clean Code Talks, 21 November 2008. http://googletesting.blogspot.com/2008/11/clean-code-talks-global-state-and.html

  13. Button, Brian (25 May 2004). "Why Singletons are Evil". Being Scott Densmore. Microsoft. Archived from the original on 15 July 2021. Retrieved 28 August 2021. https://web.archive.org/web/20210715184717/https://docs.microsoft.com/en-us/archive/blogs/scottdensmore/why-singletons-are-evil