Singleton pattern

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. 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.

A class diagram exemplifying the singleton pattern.

More specifically, the singleton pattern allows objects 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 which 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 done 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 the static method is first called.

The following snippet provides an example implementation, written in Java:[5]

public class Coin {

    private static final int ADD_MORE_COIN = 10;
    private int coin;
    private static Coin instance = new Coin(); // eagerly loads the singleton

    private Coin() {
        // private to prevent anyone else from instantiating
    }

    public static Coin getInstance() {
        return instance;
    }

    public int getCoin() {
        return coin;
    }

    public void addMoreCoin() {
        coin += ADD_MORE_COIN;
    }

    public void deductCoin() {
        coin--;
    }
}

Lazy initialization

A singleton implementation may use lazy initialization, where the instance is created when the static method is first invoked. In multi-threaded programs, this can cause race conditions that result in the creation of multiple instances. The following is a thread-safe implementation, using lazy initialization with double-checked locking, written in 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;
    }
}

Criticism

Critics 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 in all code it is visible to, requiring analysis of implementation details to determine if a dependency actually exists.[6] This increased coupling can introduce difficulties with unit testing.[7] In turn, this places restrictions on any abstraction that uses the singleton, such as preventing concurrent use of multiple instances.[7][8][9][10]

Singletons also violate the single-responsibility principle, because they are responsible for enforcing their own uniqueness, alongside their normal functionality.[7]

See also

References

  1. 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)
  2. "The Singleton design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-16.
  3. Soni, Devin (31 July 2019). "What Is a Singleton?". BetterProgramming. Retrieved 28 August 2021.
  4. Rainsberger, J.B. (1 July 2001). "Use your singletons wisely". IBM. Archived from the original on 24 February 2021. Retrieved 28 August 2021.
  5. "Are you an Android Developer and not using Singleton Class yet?". 16 April 2020.
  6. "Why Singletons Are Controversial". Google Code Archive. Archived from the original on 6 May 2021. Retrieved 28 August 2021.
  7. Button, Brian (25 May 2004). "Why Singletons are Evil". Being Scott Densmore. Microsoft. Archived from the original on 15 July 2021. Retrieved 28 August 2021.
  8. Steve Yegge. Singletons considered stupid, September 2004
  9. Hevery, Miško, "Global State and Singletons", Clean Code Talks, 21 November 2008.
  10. Contieri, Maximiliano (13 July 2020). "Singleton Pattern: The Root of All Evil". Hacker Noon. Retrieved 28 August 2021.
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.