Advanced OOP
Singleton Pattern
Ensuring a class has only one instance
Interview: Design patterns — tests understanding of singleton implementations, thread safety, and when singletons are appropriate
The Singleton pattern ensures a class has only one instance and provides a global point of access to it. While controversial (some consider it an anti-pattern), it's commonly used for shared resources like database connections, loggers, and configuration managers. Python offers multiple ways to implement it.
Implementation Approaches
- __new__ method: Override instance creation to return existing instance
- Decorator: Wrap class with a function that caches the instance
- Metaclass: Control class instantiation at the metaclass level
- Module singleton: Use a module as the singleton (Pythonic approach)
Thread Safety
In multi-threaded applications, singleton creation must be thread-safe. Use a lock (threading.Lock) around instance creation to prevent race conditions.
Common Pitfall
Singletons are often considered anti-patterns because they introduce global state, make testing harder, and hide dependencies. Consider dependency injection as an alternative.
Use Cases
Database connection pools (shared connection manager)
Application configuration (global settings)
Logging services (centralized log management)
Cache managers (shared cache instance)
Thread pools and task schedulers
Common Mistakes
Using singletons as global variables (introduces hidden dependencies)
Not making singleton creation thread-safe in multi-threaded apps
Forgetting that __init__ runs every time the class is called (even with same instance)
Making testing difficult because singletons can't be easily mocked/replaced
Not considering dependency injection as a cleaner alternative