FazBrowse Wikipedia Viewer | Main Page |
Search Wikipedia:
|
Viewing: https://en.wikipedia.org/wiki/Singleton_pattern

Singleton pattern

Contents
    Meyers singleton
    Enum singletons
    Lazy initialization
External links

A class diagram exemplifying the 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. 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(); }

Meyers singleton

edit

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.

publicfinalclass Singleton{ privateSingleton(){} privatestaticclass Holder{ staticfinalSingletonINSTANCE=newSingleton(); } publicstaticSingletoninstance(){ returnHolder.INSTANCE; } }

Enum singletons

edit

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"); } }

Lazy initialization

edit

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.

// a concrete singleton class finalclass DatabaseConnection{ privatestaticDatabaseConnectioninstance; privateDatabaseConnection(){ // database resource initialization } publicstaticsynchronizedDatabaseConnectioninstance(){ if(instance==null){ instance=newDatabaseConnection(); } returninstance; } publicvoidexecuteQuery(Stringsql){ System.out.printf("Executing: %s%n"); } } // a tightly-coupled consumer class class OrderService{ publicvoidplaceOrder(StringorderId){ // hardcoded dependency lookup makes this impossible to unit test DatabaseConnectiondb=DatabaseConnection.instance(); db.executeQuery(String.format("INSERT INTO orders VALUES ('%s')")); } }

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.
  • ↑ Scott Meyers (1997). More Effective C++. Addison Wesley. pp. 146 ff. ISBN 0-201-63371-X.
  • ↑ Class". learn.microsoft.com. Microsoft Learn. Retrieved 6 July 2026.
  • ↑ Microsoft Learn (11 March 2026). "Dependency injection guidelines". learn.microsoft.com. Microsoft Learn.
  • External links

    edit
    The Wikibook Computer Science/Design Patterns has a page on the topic of: Singleton implementations in various languages
    Wikimedia Commons has media related to Singleton pattern.
    Software design patterns
    Gang of Four
    patterns
    Creational
    Structural
    Behavioral
    Concurrency
    patterns
    Architectural
    patterns
    Other
    patterns
    Books
    People
    Communities
    See also

    View original on Wikipedia | Back | FazBrowse Home