Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Singleton pattern

From Wikipedia, the free encyclopedia
Design pattern in object-oriented software development
Aclass diagram exemplifying the singleton pattern.

Inobject-oriented programming, thesingleton pattern is asoftware design pattern that restricts theinstantiation of aclass 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.[1] The pattern is useful when exactly one object is needed to coordinate actions across a system.

More specifically, the singleton pattern allows classes to:[2]

  • Ensure they only have one instance
  • Provide easy access to that instance
  • Control their instantiation (for example, hiding theconstructors of aclass)

The term comes from themathematical concept of a singleton.

Common uses

[edit]

Singletons are often preferred toglobal variables because they do not pollute the globalnamespace (or their containing namespace). Additionally, they permitlazy allocation and initialization, whereas global variables in many languages will always consume resources.[1][3]

The singleton pattern can also be used as a basis for other design patterns, such as theabstract factory,factory method,builder andprototype 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.[4]

Implementations

[edit]

Implementations of the singleton pattern ensure that only one instance of the singleton class ever exists and typically provideglobal access to that instance.

Typically, this is accomplished by:

The instance is usually stored as a privatestatic variable; the instance is created when the variable is initialized, at some point before when the static method is first called.

ThisC++23 implementation is based on the pre-C++98 implementation in the book[citation needed].

importstd;classSingleton{public:// defines an class operation that lets clients access its unique instance.staticSingleton&get(){// may be responsible for creating its own unique instance.if(nullptr==instance)instance=newSingleton;return*instance;}Singleton(constSingleton&)=delete;// rule of threeSingleton&operator=(constSingleton&)=delete;staticvoiddestruct(){deleteinstance;instance=nullptr;}// existing interface goes hereintgetValue(){returnvalue;}voidsetValue(intvalue_){value=value_;}private:Singleton()=default;// no public constructor~Singleton()=default;// no public destructorstaticSingleton*instance;// declaration class variableintvalue;};Singleton*Singleton::instance=nullptr;// definition class variableintmain(){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 singleton[5] in C++11. The Meyers singleton has no destruct method. The program output is the same as above.

importstd;classSingleton{public:staticSingleton&get(){staticSingletoninstance;returninstance;}intgetValue(){returnvalue;}voidsetValue(intvalue_){value=value_;}private:Singleton()=default;~Singleton()=default;intvalue;};intmain(){Singleton::get().setValue(42);std::println("value={}",Singleton::get().getValue());}

Lazy initialization

[edit]

A singleton implementation may uselazy initialization in which the instance is created when the static method is first invoked. Inmultithreaded programs, this can causerace conditions that result in the creation of multiple instances. The followingJava 5+ example[6] is athread-safe implementation, using lazy initialization withdouble-checked locking.

publicclassSingleton{privatestaticvolatileSingletoninstance=null;privateSingleton(){}publicstaticSingletongetInstance(){if(instance==null){synchronized(Singleton.class){if(instance==null){instance=newSingleton();}}}returninstance;}}

Criticism

[edit]

Some consider the singleton to be ananti-pattern that introducesglobal 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.[7] This increasedcoupling can introduce difficulties withunit testing.[8] In turn, this places restrictions on any abstraction that uses the singleton, such as preventingconcurrent use of multiple instances.[8][9][10]

Singletons also violate thesingle-responsibility principle because they are responsible for enforcing their own uniqueness along with performing their normal functions.[8]

See also

[edit]

References

[edit]
  1. ^abErich 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)
  2. ^"The Singleton design pattern - Problem, Solution, and Applicability".w3sDesign.com. Retrieved2017-08-16.
  3. ^Soni, Devin (31 July 2019)."What Is a Singleton?".BetterProgramming. Retrieved28 August 2021.
  4. ^Rainsberger, J.B. (1 July 2001)."Use your singletons wisely". IBM. Archived fromthe original on 24 February 2021. Retrieved28 August 2021.
  5. ^Scott Meyers (1997).More Effective C++. Addison Wesley. pp. 146 ff.ISBN 0-201-63371-X.
  6. ^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)
  7. ^"Why Singletons Are Controversial".Google Code Archive. Archived fromthe original on 6 May 2021. Retrieved28 August 2021.
  8. ^abcButton, Brian (25 May 2004)."Why Singletons are Evil".Being Scott Densmore. Microsoft. Archived fromthe original on 15 July 2021. Retrieved28 August 2021.
  9. ^Steve Yegge.Singletons considered stupid, September 2004
  10. ^Hevery, Miško, "Global State and Singletons",Clean Code Talks, 21 November 2008.

External links

[edit]
This article'suse ofexternal links may not follow Wikipedia's policies or guidelines. Pleaseimprove this article by removingexcessive orinappropriate external links, and converting useful links where appropriate intofootnote references.(November 2016) (Learn how and when to remove this message)
Wikimedia Commons has media related toSingleton pattern.
Gang of Four
patterns
Creational
Structural
Behavioral
Concurrency
patterns
Architectural
patterns
Other
patterns
Books
People
Communities
See also
Retrieved from "https://en.wikipedia.org/w/index.php?title=Singleton_pattern&oldid=1273960207"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp