Singleton
Makes sure a class has only one instance, and gives one global way to reach it.
Why it matters
Some things should exist exactly once per program, like one configuration or one connection pool. Creating several wastes resources or causes conflicting settings.
The idea
Used for a shared resource like a configuration object or a connection pool. The class controls its own creation. Downsides: it's global state, hides dependencies, makes testing harder, and needs care with threads.
A country has one official government, and everyone refers to the same one.
You can't replace a country's government in a test, but code should be replaceable. Many teams prefer creating one instance at start-up and injecting it, which gives 'only one' without the global.
How it works
- The class keeps a hidden class-level variable for its single instance.
- When asked for an instance, it checks that variable. If it's empty, it creates the instance and stores it.
- With threads, two could check at the same moment, so creation is wrapped in a lock (and the variable is checked again inside the lock).
- Every later request returns the stored instance.
Example
A logging configuration, or a database connection pool created once per process.
Key points
- Use it for a truly single, shared resource.
- Make creation thread-safe (double-checked locking), or create the instance eagerly.
- In Python, a module is already a natural singleton.
- Often criticised as global state; prefer injecting one shared instance.
Common mistakes
- Using Singleton for things that aren't truly single, like 'the current user'.
- Hidden dependencies: code reaches for the global instead of receiving what it needs.
Not true: Singleton is a good fit for anything used all over the code, such as the current user.
In fact: Many users can be active at the same moment, so 'the current user' is not truly single. Keep Singleton for one shared resource, and pass everything else in.
In the interview
Singleton guarantees one instance with one access point, for things like configuration or a connection pool. I'd make creation thread-safe, but I usually prefer creating one instance at start-up and injecting it, because a global singleton hides dependencies and makes testing harder.
Part of Unit 6: Design patterns in the free System Design course.