> ## Documentation Index
> Fetch the complete documentation index at: https://akshanshgusain.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Singleton Pattern

> Creational Patterns

## Definition

**“Singleton pattern ensures a class has only one instance, and provides a global point of access to it”**

## Explanation

You make a class constructor private and provide a static method (e.g. `getInstance()`) that returns the sole instance.
On the first call it creates the instance; subsequent calls return the existing one. Often also make the instance
variable `static` so it’s shared. This guarantees only one object exists.

## Code

In the code below, Context uses different sorting strategies (ConcreteStrategyA and ConcreteStrategyB) to sort data.

```python theme={null}
class SingletonMeta(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            instance = super().__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]

class Singleton(metaclass=SingletonMeta):
    def some_business_logic(self):
        pass

def main():
    s1 = Singleton()
    s2 = Singleton()
    if id(s1) == id(s2):
        print("Singleton works, both references contain the same instance.")
    else:
        print("Singleton failed, references contain different instances.")

if __name__ == "__main__":
    main()

```

## Analogy

The President of a country: there is only one holder at a time, globally accessible by the population. Or the printer
spooler on a computer: one central object managing all print jobs.

## Interview Insights

**Common uses**: When exactly one instance of a class is needed (configuration manager, thread pool, logging, device driver manager). Ensures controlled access to a shared resource.\
**Advantages**: Controlled access to sole instance; lazy initialization possible. Global access like a global variable but encapsulated.\
**Disadvantages**: Hard to unit test (global state). Can hide bad design (global state). Thread safety is tricky in lazy
init. Violates single responsibility (creation & use). Often considered anti-pattern if overused.\\
