What if your system could guarantee only one shared resource instance without endless bugs and confusion?
Why Singleton pattern in LLD? - Purpose & Use Cases
Imagine you are building a system where multiple parts need to access a single shared resource, like a printer or a configuration manager. Without a controlled way to manage this, each part might create its own copy, leading to confusion and conflicts.
Manually ensuring only one instance exists is tricky. Different parts might accidentally create multiple instances, causing inconsistent states, wasted memory, and bugs that are hard to track down.
The Singleton pattern ensures that only one instance of a class exists and provides a global point of access to it. This way, all parts of the system share the same instance, avoiding duplication and conflicts.
class ConfigManager: def __init__(self): self.settings = {} cm1 = ConfigManager() cm2 = ConfigManager() # Two separate instances
class ConfigManager: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.settings = {} return cls._instance cm1 = ConfigManager() cm2 = ConfigManager() # Both refer to the same instance
It enables consistent, controlled access to shared resources across the entire system, preventing errors and improving efficiency.
Think of a printer spooler in an office: only one spooler manages all print jobs to avoid conflicts and ensure smooth printing.
Singleton ensures a single shared instance.
Prevents multiple conflicting copies.
Provides a global access point.
Practice
Singleton pattern in system design?Solution
Step 1: Understand Singleton pattern goal
The Singleton pattern is designed to restrict a class to a single instance.Step 2: Compare options with Singleton definition
Only To ensure only one instance of a class exists throughout the application matches the purpose of Singleton by ensuring one instance exists.Final Answer:
To ensure only one instance of a class exists throughout the application -> Option AQuick Check:
Singleton = single instance [OK]
- Thinking Singleton allows multiple instances
- Confusing Singleton with factory pattern
- Assuming Singleton creates new instances each call
Solution
Step 1: Identify Singleton instance method requirements
The method to get the Singleton instance must be static and publicly accessible.Step 2: Analyze options for correct access and static usage
public static getInstance() { ... } is public and static, which is correct. public void getInstance() { ... } is not static, private static getInstance() { ... } is private, static getInstance() { ... } misses access modifier.Final Answer:
public static getInstance() { ... } -> Option AQuick Check:
Singleton instance method = public static [OK]
- Making getInstance() private or non-static
- Omitting access modifier
- Using void return type instead of instance
class Logger {
static instance = null;
constructor() {}
static getInstance() {
if (this.instance === null) {
this.instance = new Logger();
}
return this.instance;
}
}
const log1 = Logger.getInstance();
const log2 = Logger.getInstance();
console.log(log1 === log2);Solution
Step 1: Understand Singleton instance creation
The first call to getInstance() creates the instance; the second returns the same instance.Step 2: Compare references of log1 and log2
Both variables point to the same instance, so strict equality returns true.Final Answer:
true -> Option BQuick Check:
Same instance check = true [OK]
- Assuming new instance created on each call
- Confusing equality with object content
- Expecting false due to separate variables
class Config {
static instance;
constructor() {}
static getInstance() {
if (!instance) {
instance = new Config();
}
return instance;
}
}Solution
Step 1: Check static variable access inside static method
Static variables must be accessed with 'this.' prefix inside static methods.Step 2: Identify missing 'this.' usage
The code uses 'instance' instead of 'this.instance', causing a reference error.Final Answer:
Missing 'this.' before 'instance' inside getInstance method -> Option CQuick Check:
Static variable access requires 'this.' [OK]
- Ignoring 'this.' prefix for static variables
- Changing constructor visibility incorrectly
- Assuming static keyword missing on method
Solution
Step 1: Understand thread safety in Singleton
In multi-threaded environments, multiple threads may create multiple instances if not synchronized.Step 2: Evaluate options for thread-safe Singleton
Double-checked locking with a volatile static instance ensures only one instance is created safely.Final Answer:
Use double-checked locking with a private static volatile instance variable -> Option DQuick Check:
Thread-safe Singleton = double-checked locking [OK]
- Ignoring thread safety in Singleton
- Making constructor public defeats Singleton
- Using global variables breaks encapsulation
Ready to prove it?
Pass the test and this pattern moves unknown
