0
0
LLDsystem_design~3 mins

Why Singleton pattern in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your system could guarantee only one shared resource instance without endless bugs and confusion?

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
class ConfigManager:
    def __init__(self):
        self.settings = {}

cm1 = ConfigManager()
cm2 = ConfigManager()  # Two separate instances
After
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
What It Enables

It enables consistent, controlled access to shared resources across the entire system, preventing errors and improving efficiency.

Real Life Example

Think of a printer spooler in an office: only one spooler manages all print jobs to avoid conflicts and ensure smooth printing.

Key Takeaways

Singleton ensures a single shared instance.

Prevents multiple conflicting copies.

Provides a global access point.