
"How would you implement a singleton pattern in mobile development? Explain how you would ensure only one instance exists, when to initialize it, and how you would handle thread safety."
A singleton ensures that a class has exactly one instance and provides a global access point to it. The core implementation challenge is preventing callers from creating multiple instances through normal construction paths.
class Singleton:
_instance = None
Eager initialization creates the instance when the class or module is loaded, which is simple but may waste memory or startup time. Lazy initialization creates it only when first requested, which is often better for mobile apps where startup performance matters.
if cls._instance is None:
cls._instance = cls()
If multiple threads can request the singleton at the same time, a naive lazy implementation can create more than one instance. A lock or language-level static initialization guarantee is needed to make creation atomic.
with cls._lock:
if cls._instance is None:
cls._instance = cls()
A good singleton design restricts direct construction and funnels all access through one method or property. In practice, this means using a private constructor where the language allows it, or documenting and enforcing a single creation path.
Singletons are convenient for shared services like configuration, logging, or networking, but they can hide dependencies and make tests harder. In interviews, it is important to mention reset hooks, dependency injection, or interface-based wrappers for better testability.