Design Patterns — Fast Recall (Python)
Singleton — exactly one instance
- What: guarantee a class has one instance with a global access point.
- Why / when: a single shared resource — config, logger, DB connection pool, cache. Creating many would waste resources or cause inconsistent state.
- Python truth: a module is already a singleton (imported once, cached) — often the cleanest answer in interviews.
- Gotcha: it's global state → hard to test, hidden coupling, thread-safety needs a lock. Mention these to sound senior.
1class Config:
2 _instance = None
3
4 def __new__(cls):
5 if cls._instance is None:
6 cls._instance = super().__new__(cls)
7 cls._instance.settings = {} # init once
8 return cls._instance
9
10a, b = Config(), Config()
11assert a is b # same object
12a.settings["env"] = "prod"
13print(b.settings) # {'env': 'prod'}