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.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.\