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
(section)
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!
== 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>
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)