Singleton Pattern
Some things should exist only once in a program: the configuration loaded at startup, the counter that hands out ticket numbers, the pool of database connections. If a second copy appears by accident, two counters can hand out the same ticket number, and two pools can open twice as many connections as the database allows.
The Singleton pattern makes a class guarantee that it has exactly one instance, and gives the whole program one way to reach it. It is the best-known pattern and the most criticized one. Interviewers bring it up for two reasons: to see whether you can create it safely when several threads race for it, and to see whether you know why you usually shouldn't.
1️⃣ In one sentence: make the constructor private, keep the single instance in a static field, and hand it out through one static method, so there is never more than one and everyone gets the same one.
The Problem It Solves
Here is a parking lot where every entry gate prints tickets with an ID. The first version gives each gate its own generator:
class TicketIdGenerator:
def __init__(self) -> None:
self.next_id = 1
def next(self) -> str:
ticket_id = f"T-{self.next_id:06d}"
self.next_id += 1
return ticket_id
class EntryGate:
def __init__(self, gate_id: str) -> None:
self.gate_id = gate_id
self.ids = TicketIdGenerator() # each gate makes its own
def issue(self, plate: str) -> Ticket:
return Ticket(self.ids.next(), plate, self.gate_id)
The north gate issues T-000001. So does the south gate. When the driver from the south gate pays, the system
finds the north gate's ticket and charges the wrong car.
The bug is that the rule "there is one sequence of ticket numbers" lives only in our heads. Nothing in the code stops a second generator from being created. Singleton turns that rule into code, and it does two separate things:
- Exactly one instance: the class refuses to be constructed a second time.
- Global access: any code can reach that instance without being handed it.
Keep these apart. The first is what fixes the bug. The second is what causes most of the trouble later.