Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Singleton pattern
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Design pattern in object-oriented software development}} [[File:Singleton UML class diagram.svg|thumb|A [[class diagram]] exemplifying the singleton pattern.]] In [[object-oriented programming]], the '''singleton pattern''' is a [[software design pattern]] that restricts the [[Instantiation (computer science)|instantiation]] of a [[Class (computer programming)|class]] to a singular instance. It is one of the well-known [[Design Patterns|"Gang of Four" design patterns]], which describe how to solve recurring problems in object-oriented software.<ref name="GoF">{{cite book |author=Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides |url=https://archive.org/details/designpatternsel00gamm/page/127 |title=Design Patterns: Elements of Reusable Object-Oriented Software |publisher=Addison Wesley |year=1994 |isbn=0-201-63361-2 |pages=[https://archive.org/details/designpatternsel00gamm/page/127 127ff] |url-access=registration}}</ref> The pattern is useful when exactly one object is needed to coordinate actions across a system. More specifically, the singleton pattern allows classes to:<ref>{{cite web |title=The Singleton design pattern - Problem, Solution, and Applicability |url=http://w3sdesign.com/?gr=c05&ugr=proble |access-date=2017-08-16 |website=w3sDesign.com}}</ref> * Ensure they only have one instance * Provide easy access to that instance * Control their instantiation (for example, hiding the [[Constructor (object-oriented programming)|constructors]] of a [[Class (computer programming)|class]]) The term comes from the [[Singleton (mathematics)|mathematical concept of a singleton]]. == 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 evaluation|lazy]] allocation and initialization, whereas global variables in many languages will always consume resources.<ref name="GoF" /><ref name="devin">{{cite news |last1=Soni |first1=Devin |date=31 July 2019 |title=What Is a Singleton? |work=BetterProgramming |url=https://betterprogramming.pub/what-is-a-singleton-2dc38ca08e92 |access-date=28 August 2021}}</ref> The singleton pattern can also be used as a basis for other design patterns, such as the [[Abstract factory pattern|abstract factory]], [[Factory method pattern|factory method]], [[Builder pattern|builder]] and [[Prototype pattern|prototype]] patterns. [[Facade pattern|Facade]] objects are also often singletons because only one facade object is required. [[Log file|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.<ref name="rainsberger">{{cite news |last1=Rainsberger |first1=J.B. |title=Use your singletons wisely |url=https://www.ibm.com/developerworks/library/co-single/ |access-date=28 August 2021 |publisher=IBM |date=1 July 2001 |archive-url=https://web.archive.org/web/20210224180356/https://www.ibm.com/developerworks/library/co-single/ |archive-date=24 February 2021}}</ref> == Implementations == Implementations of the singleton pattern ensure that only one instance of the singleton class ever exists and typically provide [[Global scope|global access]] to that instance. Typically, this is accomplished by: * Declaring all [[Constructor (object-oriented programming)|constructors]] of the class to be [[Private member|private]], which prevents it from being instantiated by other objects * Providing a [[static method]] that returns a [[Reference (computer science)|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++23]] implementation is based on the pre-C++98 implementation in the book {{Citation needed|reason=the book is ambiguous here.|date=March 2024}}. <syntaxhighlight lang="Cpp"> 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(); } </syntaxhighlight> The program output is <syntaxhighlight lang="c++"> value=42 </syntaxhighlight> This is an implementation of the Meyers singleton<ref>{{cite book |author=Scott Meyers |title=More Effective C++ |publisher=Addison Wesley |year=1997 |isbn=0-201-63371-X |pages= 146 ff}}</ref> in C++11. The Meyers singleton has no destruct method. The program output is the same as above. <syntaxhighlight lang="Cpp"> 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()); } </syntaxhighlight> === Lazy initialization === A singleton implementation may use [[lazy initialization]] in which the instance is created when the static method is first invoked. In [[Multithreading (software)|multithreaded]] programs, this can cause [[Race condition|race conditions]] that result in the creation of multiple instances. The following [[Java_version_history#Java_5|Java 5+]] example<ref>{{Cite book|author=Eric Freeman, Elisabeth Freeman, Kathy Sierra, and Bert Bates|title=Head First Design Patterns|publisher=O'Reilly Media, Inc|date=October 2004|edition=First|chapter=5: One of a Kind Objects: The Singleton Pattern|page=182|isbn=978-0-596-00712-6|chapter-url=https://books.google.com/books?id=GGpXN9SMELMC&pg=PA182}}</ref> is a [[Thread safety|thread-safe]] implementation, using lazy initialization with [[double-checked locking]]. <syntaxhighlight lang="java"> 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; } } </syntaxhighlight> == Criticism == Some consider the singleton to be an [[anti-pattern]] that introduces [[global variables|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.<ref name="google">{{cite web |title=Why Singletons Are Controversial |url=https://code.google.com/archive/p/google-singleton-detector/wikis/WhySingletonsAreControversial.wiki |archive-url=https://web.archive.org/web/20210506162753/https://code.google.com/archive/p/google-singleton-detector/wikis/WhySingletonsAreControversial.wiki |archive-date=6 May 2021 |access-date=28 August 2021 |website=Google Code Archive}}</ref> This increased [[Coupling (computer programming)|coupling]] can introduce difficulties with [[unit testing]].<ref name="button">{{cite news |last1=Button |first1=Brian |date=25 May 2004 |title=Why Singletons are Evil |work=Being Scott Densmore |publisher=Microsoft |url=https://docs.microsoft.com/en-us/archive/blogs/scottdensmore/why-singletons-are-evil |access-date=28 August 2021 |archive-url=https://web.archive.org/web/20210715184717/https://docs.microsoft.com/en-us/archive/blogs/scottdensmore/why-singletons-are-evil |archive-date=15 July 2021}}</ref> In turn, this places restrictions on any abstraction that uses the singleton, such as preventing [[Concurrency_(computer_science)|concurrent]] use of multiple instances.<ref name="button" /><ref>Steve Yegge. [http://steve.yegge.googlepages.com/singleton-considered-stupid Singletons considered stupid], September 2004</ref><ref name="googletesting.blogspot.com">Hevery, Miško, "[http://googletesting.blogspot.com/2008/11/clean-code-talks-global-state-and.html Global State and Singletons]", ''Clean Code Talks'', 21 November 2008.</ref> Singletons also violate the [[single-responsibility principle]] because they are responsible for enforcing their own uniqueness along with performing their normal functions.<ref name="button" /> == See also == * [[Initialization-on-demand holder idiom]] * [[Multiton pattern]] * [[Software design pattern]] == References == {{reflist}} == External links == {{external links|date=November 2016}} {{wikibooks|Computer Science/Design Patterns|Singleton|Singleton implementations in various languages}} {{commons category}} * Complete article "[https://howtodoinjava.com/design-patterns/creational/singleton-design-pattern-in-java/ Java Singleton Pattern Explained]" * Four different ways to implement singleton in Java "[https://web.archive.org/web/20150709155148/http://www.javaexperience.com/design-patterns-singleton-design-pattern/ Ways to implement singleton in Java]" * Book extract: [https://csharpindepth.com/Articles/Singleton Implementing the Singleton Pattern in C#] by Jon Skeet * [https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ff650849(v=pandp.10) Singleton at Microsoft patterns & practices Developer Center] * IBM article "[https://www.ibm.com/developerworks/library/j-dcl/ Double-checked locking and the Singleton pattern]" by Peter Haggar * {{cite web |last1=Geary |first1=David |date=2003-04-25 |df=mdy |url=https://www.infoworld.com/article/2073352/core-java-simply-singleton.html |title=How to navigate the deceptively simple Singleton pattern |department=Java Design Patterns |work=[[JavaWorld]] |access-date=2020-07-21}} * [https://code.google.com/archive/p/google-singleton-detector/ Google Singleton Detector] (analyzes [[Java bytecode]] to detect singletons) {{Design Patterns Patterns}} {{DEFAULTSORT:Singleton Pattern}} [[Category:Software design patterns]] [[Category:Anti-patterns]] [[Category:Articles with example Java code]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Citation needed
(
edit
)
Template:Cite book
(
edit
)
Template:Cite news
(
edit
)
Template:Cite web
(
edit
)
Template:Commons category
(
edit
)
Template:Design Patterns Patterns
(
edit
)
Template:External links
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)
Template:Sister project
(
edit
)
Template:Wikibooks
(
edit
)