<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>http://debianws.lexgopc.com/wiki1463/index.php?action=history&amp;feed=atom&amp;title=Singleton_pattern</id>
	<title>Singleton pattern - Revision history</title>
	<link rel="self" type="application/atom+xml" href="http://debianws.lexgopc.com/wiki1463/index.php?action=history&amp;feed=atom&amp;title=Singleton_pattern"/>
	<link rel="alternate" type="text/html" href="http://debianws.lexgopc.com/wiki1463/index.php?title=Singleton_pattern&amp;action=history"/>
	<updated>2026-12-01T08:55:05Z</updated>
	<subtitle>Revision history for this page on the wiki</subtitle>
	<generator>MediaWiki 1.46.3</generator>
	<entry>
		<id>http://debianws.lexgopc.com/wiki1463/index.php?title=Singleton_pattern&amp;diff=43452&amp;oldid=prev</id>
		<title>~2026-49174-72: /* Implementations */</title>
		<link rel="alternate" type="text/html" href="http://debianws.lexgopc.com/wiki1463/index.php?title=Singleton_pattern&amp;diff=43452&amp;oldid=prev"/>
		<updated>2026-09-11T01:36:34Z</updated>

		<summary type="html">&lt;p&gt;&lt;span class=&quot;autocomment&quot;&gt;Implementations&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;b&gt;New page&lt;/b&gt;&lt;/p&gt;&lt;div&gt;{{Short description|Programming technique to restrict a class to a single instance}}&lt;br /&gt;
[[File:Singleton UML class diagram.svg|thumb|A [[class diagram]] exemplifying the singleton pattern.]]&lt;br /&gt;
&lt;br /&gt;
In [[object-oriented programming]], the &amp;#039;&amp;#039;&amp;#039;singleton pattern&amp;#039;&amp;#039;&amp;#039; is a [[software design pattern]] that restricts the [[Instantiation (computer science)|instantiation]] of a [[Class (programming)|class]] to a singular instance. It is one of the well-known [[Design Patterns|&amp;quot;Gang of Four&amp;quot; design patterns]], which describe how to solve recurring problems in object-oriented software.&amp;lt;ref name=&amp;quot;GoF&amp;quot;&amp;gt;{{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}}&amp;lt;/ref&amp;gt; The pattern is useful when exactly one object is needed to coordinate actions across a system.&lt;br /&gt;
&lt;br /&gt;
More specifically, the singleton pattern allows classes to:&amp;lt;ref&amp;gt;{{cite web |title=The Singleton design pattern - Problem, Solution, and Applicability |url=http://w3sdesign.com/?gr=c05&amp;amp;ugr=proble |access-date=2017-08-16 |website=w3sDesign.com}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Ensure they only have one instance&lt;br /&gt;
* Provide easy access to that instance&lt;br /&gt;
* Control their instantiation (for example, hiding the [[Constructor (object-oriented programming)|constructors]] of a [[Class (programming)|class]])&lt;br /&gt;
&lt;br /&gt;
The term comes from the [[Singleton (mathematics)|mathematical concept of a singleton]].&lt;br /&gt;
&lt;br /&gt;
== Common uses ==&lt;br /&gt;
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.&amp;lt;ref name=&amp;quot;GoF&amp;quot; /&amp;gt;&amp;lt;ref name=&amp;quot;devin&amp;quot;&amp;gt;{{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}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
[[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.&amp;lt;ref name=&amp;quot;rainsberger&amp;quot;&amp;gt;{{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}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Implementations ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Typically, this is accomplished by:&lt;br /&gt;
* Declaring all [[Constructor (object-oriented programming)|constructors]] of the class to be [[Private member|private]], which prevents it from being instantiated by other objects&lt;br /&gt;
* Providing a [[static method]] that returns a [[Reference (computer science)|reference]] to the instance&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== Traditional implementation ===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;cpp&amp;quot;&amp;gt;&lt;br /&gt;
import std;&lt;br /&gt;
&lt;br /&gt;
class Singleton {&lt;br /&gt;
private:&lt;br /&gt;
    Singleton() = default; // no public constructor&lt;br /&gt;
    ~Singleton() = default; // no public destructor&lt;br /&gt;
    inline static Singleton* inst = nullptr; // declaration class variable&lt;br /&gt;
    int value;&lt;br /&gt;
public:&lt;br /&gt;
    // defines a class operation that lets clients access its unique instance.&lt;br /&gt;
    static Singleton&amp;amp; instance() {&lt;br /&gt;
        if (!inst) {&lt;br /&gt;
            inst = new Singleton();&lt;br /&gt;
        }&lt;br /&gt;
        return *inst;&lt;br /&gt;
    }&lt;br /&gt;
  &lt;br /&gt;
    Singleton(const Singleton&amp;amp;) = delete(&amp;quot;Copy construction disabled&amp;quot;);&lt;br /&gt;
    Singleton&amp;amp; operator=(const Singleton&amp;amp;) = delete(&amp;quot;Copy assignment disabled&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
    static void reset() {&lt;br /&gt;
        delete inst;&lt;br /&gt;
        inst = nullptr;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // existing interface goes here&lt;br /&gt;
    [[nodiscard]]&lt;br /&gt;
    int getValue() const noexcept {&lt;br /&gt;
        return value;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    void setValue(int v) noexcept {&lt;br /&gt;
        value = v;&lt;br /&gt;
    }&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
int main() {&lt;br /&gt;
    Singleton::instance().setValue(42);&lt;br /&gt;
    std::println(&amp;quot;value = {}&amp;quot;, Singleton::instance().getValue()); // prints &amp;quot;value = 42&amp;quot;&lt;br /&gt;
    Singleton::reset();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Meyers singleton ===&lt;br /&gt;
This is an implementation of the Meyers singleton, so named after Scott Meyers, author of &amp;#039;&amp;#039;More Effective C++&amp;#039;&amp;#039;, due to his recommendation of this implementation.&amp;lt;ref&amp;gt;{{cite book |author=Scott Meyers |title=More Effective C++ |publisher=Addison Wesley |year=1997 |isbn=0-201-63371-X |pages= 146 ff}}&amp;lt;/ref&amp;gt; The Meyers singleton has no destructor method. The program output is the same as above.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;Cpp&amp;quot;&amp;gt;&lt;br /&gt;
import std;&lt;br /&gt;
&lt;br /&gt;
class Singleton {&lt;br /&gt;
private:&lt;br /&gt;
    Singleton() = default;&lt;br /&gt;
    ~Singleton() = default;&lt;br /&gt;
    int value;&lt;br /&gt;
public:&lt;br /&gt;
    static Singleton&amp;amp; instance() {&lt;br /&gt;
        static Singleton instance;&lt;br /&gt;
        return instance;&lt;br /&gt;
    }&lt;br /&gt;
  &lt;br /&gt;
    [[nodiscard]]&lt;br /&gt;
    int getValue() const noexcept {&lt;br /&gt;
        return value;&lt;br /&gt;
    }&lt;br /&gt;
  &lt;br /&gt;
    void setValue(int v) noexcept {&lt;br /&gt;
        value = v;&lt;br /&gt;
    }&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
int main() {&lt;br /&gt;
    Singleton::instance().setValue(42);&lt;br /&gt;
    std::println(&amp;quot;value = {}&amp;quot;, Singleton::instance().getValue()); // prints &amp;quot;value = 42&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While the Meyers singleton is mostly unique to C++ due to C++&amp;#039;s function-local &amp;lt;syntaxhighlight lang=&amp;quot;cpp&amp;quot; inline&amp;gt;static&amp;lt;/syntaxhighlight&amp;gt; variables with lazy thread-safe initialization, it can still be emulated in other languages. For example, in [[Java (programming language)|Java]], one can use the [[initialization-on-demand holder idiom]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private Singleton() {}&lt;br /&gt;
&lt;br /&gt;
    private static class Holder {&lt;br /&gt;
        static final Singleton INSTANCE = new Singleton();&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public static Singleton instance() {&lt;br /&gt;
        return Holder.INSTANCE;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Lazy initialization ===&lt;br /&gt;
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&amp;lt;ref&amp;gt;{{Cite book|author=Eric Freeman, Elisabeth Freeman, Kathy Sierra, and Bert Bates|title=Head First Design Patterns|publisher=O&amp;#039;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&amp;amp;pg=PA182}}&amp;lt;/ref&amp;gt; is a [[Thread safety|thread-safe]] implementation, using lazy initialization with [[double-checked locking]].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
    private static volatile Singleton instance = null;&lt;br /&gt;
&lt;br /&gt;
    private Singleton() {}&lt;br /&gt;
&lt;br /&gt;
    public static Singleton instance() {&lt;br /&gt;
        if (instance == null) {&lt;br /&gt;
            synchronized (Singleton.class) {&lt;br /&gt;
                if (instance == null) {&lt;br /&gt;
                    instance = new Singleton();&lt;br /&gt;
                }&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
        return instance;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a manner similar to the Meyers singleton, one can use &amp;lt;code&amp;gt;System.Lazy&amp;lt;T&amp;gt;&amp;lt;/code&amp;gt; in [[C Sharp (programming language)|C#]] to use lazy initialization:&amp;lt;ref&amp;gt;{{Cite web|title=Lazy&amp;lt;T&amp;gt; Class|url=https://learn.microsoft.com/en-us/dotnet/api/system.lazy-1|publisher=Microsoft Learn|website=learn.microsoft.com|author=Microsoft Learn|access-date=6 July 2026}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;csharp&amp;quot;&amp;gt;&lt;br /&gt;
using System;&lt;br /&gt;
&lt;br /&gt;
public sealed class Singleton&lt;br /&gt;
{&lt;br /&gt;
    private static readonly Lazy&amp;lt;Singleton&amp;gt; _instance = new(() =&amp;gt; new Singleton());&lt;br /&gt;
&lt;br /&gt;
    public static Singleton Instance =&amp;gt; _instance.Value;&lt;br /&gt;
&lt;br /&gt;
    private Singleton() {}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Criticism ==&lt;br /&gt;
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.&amp;lt;ref name=&amp;quot;google&amp;quot;&amp;gt;{{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}}&amp;lt;/ref&amp;gt; This increased [[Coupling (computer programming)|coupling]] can introduce difficulties with [[unit testing]].&amp;lt;ref name=&amp;quot;button&amp;quot;&amp;gt;{{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}}&amp;lt;/ref&amp;gt; In turn, this places restrictions on any abstraction that uses the singleton, such as preventing [[Concurrency_(computer_science)|concurrent]] use of multiple instances.&amp;lt;ref name=&amp;quot;button&amp;quot; /&amp;gt;&amp;lt;ref&amp;gt;Steve Yegge. [http://steve.yegge.googlepages.com/singleton-considered-stupid Singletons considered stupid], September 2004&amp;lt;/ref&amp;gt;&amp;lt;ref name=&amp;quot;googletesting.blogspot.com&amp;quot;&amp;gt;Hevery, Miško, &amp;quot;[http://googletesting.blogspot.com/2008/11/clean-code-talks-global-state-and.html Global State and Singletons]&amp;quot;, &amp;#039;&amp;#039;Clean Code Talks&amp;#039;&amp;#039;, 21 November 2008.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Singletons also violate the [[single-responsibility principle]] because they are responsible for enforcing their own uniqueness along with performing their normal functions.&amp;lt;ref name=&amp;quot;button&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Avoidance through dependency injection ===&lt;br /&gt;
[[Dependency injection]] can be used to avoid the singleton pattern. The singleton pattern enforces a structural restriction of only one instance of a class, but dependency injection focuses on how dependencies are passed around, avoiding the necessity of objects to look up their own global state.&amp;lt;ref&amp;gt;{{Cite web|title=Dependency injection guidelines|url=https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/guidelines|author=Microsoft Learn|website=learn.microsoft.com|publisher=Microsoft Learn|date=11 March 2026}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, in the following example, the &amp;lt;code&amp;gt;OrderService&amp;lt;/code&amp;gt; is tightly coupled to &amp;lt;code&amp;gt;DatabaseConnection&amp;lt;/code&amp;gt;; the database cannot be swapped and a different instance cannot be used.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// a concrete singleton class&lt;br /&gt;
class DatabaseConnection {&lt;br /&gt;
    private static DatabaseConnection instance;&lt;br /&gt;
&lt;br /&gt;
    private DatabaseConnection() {&lt;br /&gt;
        // database resource initialization&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public static synchronized DatabaseConnection instance() {&lt;br /&gt;
        if (instance == null) {&lt;br /&gt;
            instance = new DatabaseConnection();&lt;br /&gt;
        }&lt;br /&gt;
        return instance;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void executeQuery(String sql) {&lt;br /&gt;
        System.out.printf(&amp;quot;Executing: %s%n&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// a tightly-coupled consumer class&lt;br /&gt;
class OrderService {&lt;br /&gt;
    public void placeOrder(String orderId) {&lt;br /&gt;
        // hardcoded dependency lookup makes this impossible to unit test&lt;br /&gt;
        DatabaseConnection db = DatabaseConnection.instance();&lt;br /&gt;
        db.executeQuery(String.format(&amp;quot;INSERT INTO orders VALUES (&amp;#039;%s&amp;#039;)&amp;quot;));&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Dependency injection avoids asking how the database is created, or how many instances exist, and only asks for the &amp;lt;code&amp;gt;Database&amp;lt;/code&amp;gt; [[Interface (object-oriented programming)|interface]] in its constructor:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// an abstract interface&lt;br /&gt;
interface Database {&lt;br /&gt;
    void executeQuery(String sql);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// implement the concrete class (no singleton logic)&lt;br /&gt;
class SqlDatabase implements Database {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void executeQuery(String sql) {&lt;br /&gt;
        System.out.println(&amp;quot;Executing SQL: %s&amp;quot;, sql);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// the consumer class accepts dependency via constructor injection&lt;br /&gt;
class OrderService {&lt;br /&gt;
    private final Database db;&lt;br /&gt;
&lt;br /&gt;
    // The dependency is injected from the outside&lt;br /&gt;
    public OrderService(Database db) {&lt;br /&gt;
        this.db = db;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public void placeOrder(String orderId) {&lt;br /&gt;
        db.executeQuery(String.format(&amp;quot;INSERT INTO orders VALUES (&amp;#039;%s&amp;#039;)&amp;quot;, orderId));&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== See also ==&lt;br /&gt;
* [[Initialization-on-demand holder idiom]]&lt;br /&gt;
* [[Multiton pattern]]&lt;br /&gt;
* [[Dependency injection]]&lt;br /&gt;
* [[Software design pattern]]&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
{{reflist}}&lt;br /&gt;
&lt;br /&gt;
== External links ==&lt;br /&gt;
{{wikibooks|Computer Science/Design Patterns|Singleton|Singleton implementations in various languages}}&lt;br /&gt;
{{commons category}}&lt;br /&gt;
* Complete article &amp;quot;[https://howtodoinjava.com/design-patterns/creational/singleton-design-pattern-in-java/ Java Singleton Pattern Explained]&amp;quot; &lt;br /&gt;
* Four different ways to implement singleton in Java &amp;quot;[https://web.archive.org/web/20150709155148/http://www.javaexperience.com/design-patterns-singleton-design-pattern/ Ways to implement singleton in Java]&amp;quot; &lt;br /&gt;
&lt;br /&gt;
{{Design Patterns Patterns}}&lt;br /&gt;
&lt;br /&gt;
{{DEFAULTSORT:Singleton Pattern}}&lt;br /&gt;
[[Category:Software design patterns]]&lt;br /&gt;
[[Category:Anti-patterns]]&lt;br /&gt;
[[Category:Articles with example Java code]]&lt;/div&gt;</summary>
		<author><name>~2026-49174-72</name></author>
	</entry>
</feed>