| FazBrowse Wikipedia Viewer | Main Page | | |
| Viewing: https://en.wikipedia.org/wiki/Singleton_pattern |
| Contents |
|---|
| Meyers singleton |
| Enum singletons |
| Lazy initialization |
| External links |
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. The pattern is useful when exactly one object is needed to coordinate actions across a system.
More specifically, the singleton pattern allows classes to:
The term comes from the mathematical concept of a singleton.
class and publicfinalclass Singleton{ privatestaticfinalSingletonINSTANCE=newSingleton();// declaration class variable privateintvalue; privateSingleton(){} // defines a class operation that lets clients access its unique instance publicstaticSingletoninstance(){ returnINSTANCE; } publicintgetValue(){ returnvalue; } publicvoidsetValue(intv){ value=v; } }In C++, the implementation is more intricate; the Java implementation is implicitly thread-safe, but the eager singleton in C++ requires double-checked locking with lock/mutex to guarantee thread safety. Additionally, special member functions must be made either importstd; usingstd::mutex; usingstd::scoped_lock; classSingletonfinal{ private: inlinestaticSingleton*inst=nullptr; inlinestaticmutexm;// Mutex for syncrhonized initialization intvalue; Singleton()=default;// no public constructor ~Singleton()=default;// no public destructor public: staticSingleton&instance(){ // First check (for pre-initialization) if(!inst){ // Lock the mutex before creation scoped_lock<mutex>lock(m); // Second check uses a lock to prevent race conditions if(!inst){ inst=newSingleton(); } } // After initialization, checks are bypassed entirely return*inst; } Singleton(constSingleton&)=delete("Copy construction disabled"); Singleton&operator=(constSingleton&)=delete("Copy assignment disabled"); // optional cleanup method; not necessary staticvoidreset(){ scoped_lock<mutex>lock(m); deleteinst; inst=nullptr; } [[nodiscard]] intgetValue()constnoexcept{ returnvalue; } voidsetValue(intv)noexcept{ value=v; } }; intmain(){ Singleton::instance().setValue(42); std::println("value = {}",Singleton::instance().getValue());// prints "value = 42" Singleton::reset(); }
This is an implementation of the Meyers singleton, so named after Scott Meyers, author of More Effective C++, due to his recommendation of this implementation. This implementation is lazily instantiated, only constructing the instance the first time the execution reaches the definition line inside instance(), never allocating/constructing the object if instance() is never called. This initialization is guaranteed (since C++11) to be thread-safe without needing manual locks, through function-local static initialization. The Meyers singleton does not include a reset() method (unlike the earlier traditional implementation; however, one can be implemented if the singleton is held using a unique pointer), and destruction occurs at program exit (like all static variables). The program output is the same as above.
In Java, because enums are full classes (rather than just integral constants), an publicenumSingleton{ INSTANCE; // fields and methods can be added here publicvoidfoo(){ System.out.println("Some singleton operation here"); } }
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 is a thread-safe implementation, using lazy initialization with double-checked locking.
Dependency injection avoids asking how the database is created, or how many instances exist, and only asks for the Database interface in its constructor:
"The Singleton design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-16.| Creational | |
|---|---|
| Structural | |
| Behavioral |
| View original on Wikipedia | Back | FazBrowse Home |