The singleton pattern makes sure a class only ever has one instance, and gives the whole program a single way to reach it.
It is one of the best-known design patterns and one of the most argued about, because the thing that makes it convenient, one object every part of the code can reach, is also what makes it hard to test.
What the pattern promises
The singleton pattern makes two promises:
- Only one instance exists. However many times code asks for the object, it gets the same one back.
- There is one well-known way to get it, usually a class method such as
get_instance()or a name defined at module level.
The second promise is what separates a singleton from an object you happen to create once. You don't pass it around: any part of the code can ask for it.
The pattern comes from the 1994 book Design Patterns by the 'Gang of Four' (Gamma, Helm, Johnson and Vlissides). It is one of their creational patterns, the group about how objects get created.
Why you'd want only one
Some things in a program should exist only once:
- Configuration: settings are loaded from a file or the environment at start-up. If two parts of the app each loaded their own copy, they could disagree.
- A database connection pool: opening connections is slow, and the database allows only so many. One shared pool hands them out and takes them back.
- A logger: every module writes to the same log, with the same format and destination.
- A cache, which only helps if everyone reads from and writes to the same one.
What these share: the object holds shared state or an expensive resource, and having two of them would be wasteful or wrong.
Wondering how this was made? How we make these