Stats

167 Contributors: 6 Sunday, January 8, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Singleton Design Pattern

Remarks

A Singleton is designed to ensure a class only has one instance and provides a global point of access to it. If you only require one instance or a convenient global point of access, but not both, consider other options before turning to the singleton.

Global variables can make it harder to reason about code. For example, if one of the calling functions isn't happy with the data it's receiving from a Singleton, you now have to track down what is first giving the singleton bad data in the first place.

Singletons also encourage coupling, a term used to describe two components of code that are joined together thus reducing each components own measure of self-containment.

Singletons aren't concurrency friendly. When a class has a global point of access, every thread has the ability to access it which can lead to deadlocks and race conditions.

Lastly, lazy initialization can cause performance issues if initialized at the wrong time. Removing lazy initialization also removes some of the features that do make Singleton's interesting in the first place, such as polymorphism (see Subclasses).

Sources: Game Programming Patterns by Robert Nystrom

Related Examples