Singleton pattern

In object-oriented programming, the singleton pattern is a software design pattern that restricts the instantiation of a class 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 the constructors of a class)
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 (or their containing namespace). Additionally, they permit lazy 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 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.[4]
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, which prevents it from being instantiated by other objects
- Providing a static method that returns a 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].
import std;
class Singleton {
private:
Singleton() = default; // no public constructor
~Singleton() = default; // no public destructor
inline static Singleton* instance = nullptr; // declaration class variable
int value;
public:
// defines a class operation that lets clients access its unique instance.
static Singleton& getInstance() {
if (!instance) {
instance = new Singleton();
}
return *instance;
}
Singleton(const Singleton&) = delete("Copy construction disabled");
Singleton& operator=(const Singleton&) = delete("Copy assignment disabled");
static void destroy() {
delete instance;
instance = nullptr;
}
// existing interface goes here
[[nodiscard]]
int getValue() const noexcept {
return value;
}
void setValue(int newValue) noexcept {
value = newValue;
}
};
int main() {
Singleton::getInstance().setValue(42);
std::println("value = {}", Singleton::getInstance().getValue());
Singleton::destroy();
}
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.
import std;
class Singleton {
private:
Singleton() = default;
~Singleton() = default;
int value;
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
[[nodiscard]]
int getValue() const noexcept {
return value;
}
void setValue(int newValue) noexcept {
value = newValue;
}
};
int main() {
Singleton::getInstance().setValue(42);
std::println("value = {}", Singleton::getInstance().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+ example[6] 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.[7] This increased coupling can introduce difficulties with unit testing.[8] In turn, this places restrictions on any abstraction that uses the singleton, such as preventing concurrent use of multiple instances.[8][9][10]
Singletons also violate the single-responsibility principle because they are responsible for enforcing their own uniqueness along with performing their normal functions.[8]
See also
References
- ^ a b 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) - ^ "The Singleton design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-16.
- ^ Soni, Devin (31 July 2019). "What Is a Singleton?". BetterProgramming. Retrieved 28 August 2021.
- ^ Rainsberger, J.B. (1 July 2001). "Use your singletons wisely". IBM. Archived from the original on 24 February 2021. Retrieved 28 August 2021.
- ^ Scott Meyers (1997). More Effective C++. Addison Wesley. pp. 146 ff. ISBN 0-201-63371-X.
- ^ 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) - ^ "Why Singletons Are Controversial". Google Code Archive. Archived from the original on 6 May 2021. Retrieved 28 August 2021.
- ^ Steve Yegge. Singletons considered stupid, September 2004
- ^ Hevery, Miško, "Global State and Singletons", Clean Code Talks, 21 November 2008.
External links
- Complete article "Java Singleton Pattern Explained"
- Four different ways to implement singleton in Java "Ways to implement singleton in Java"
Content Disclaimer
Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.
- The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
- There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
- It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
- Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
- Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.