What is the Singleton pattern, and what are its intended use cases along with its commonly cited drawbacks?
Short answer
The Singleton pattern ensures a class has only one single instance throughout the application and provides a global point of access to that instance, which is sometimes used for things like a single shared database connection, though it is also commonly criticized for…
Advertisement
AModel answer
The Singleton pattern ensures a class has only one single instance throughout the application and provides a global point of access to that instance, which is sometimes used for things like a single shared database connection, though it is also commonly criticized for introducing hidden global state that makes testing more difficult and creating tight coupling to that specific class throughout the codebase, leading many modern developers to prefer dependency injection instead for similar use cases.
class Database {
private static ?Database $instance = null;
public static function getInstance(): self {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}Real-world example
An older codebase uses a Singleton for its database connection, and a team refactoring that codebase toward better testability replaces it with a properly injected database dependency, immediately making previously untestable classes much easier to test in isolation.
Likely follow-ups
- Why is the Singleton pattern often considered an anti pattern by modern developers?
- What is a better alternative to Singleton for managing a genuinely shared resource?
Related topics