The Singleton pattern ensures a class has only one instance, and provides a global point of access to it.
This is all pretty simple.
A singleton-class has its constructors (cstr, cpy, move...) private so that it cannot be instatiated. The only way to use it is by calling a static method that is responsible of instanciating the required instance.
static Singleton& getInstance(void);
The Singleton pattern has some advantages over global variables :
- It enforces that only one instance of the class can be instantiated.
- It provides thread-safe access to the object's global state.
- It prevents the global namespace from being polluting.
All in all, the Singleton pattern is considered to reflect a poor design choice as it is only a way to store global data.
There are several alternatives to the Singleton pattern :
- Dependency injection
- Monostate pattern
- Session context
Some interesting links on why singleton pattern is evil :