Interview frequency: …
Short answer
It introduces shared global mutable state that hides dependencies and makes isolated testing difficult, as well as introducing thread-safety complexity.
Explanation
Singleton violates SRP because it manages its own lifecycle in addition to its main job. In multithreaded environments and unit tests, global objects retain state between tests, causing random, cascading failures. Modern systems use DI containers to register services with a Singleton lifecycle while keeping the service code itself ordinary, testable, and mockable.
Code example
class Singleton {
private static instance: Singleton;
private constructor() {} // Prevent direct instantiation
public static getInstance(): Singleton {
if (!Singleton.instance) Singleton.instance = new Singleton();
return Singleton.instance;
}
}Common mistakes
- Implementing Singleton in a multithreaded environment without proper synchronization, potentially creating multiple instances concurrently due to a race condition.