Singleton
medium 60 minOne object and one way to reach it.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Who asks, who builds, and how many objects exist.
Operations
One for three
Three services of one program ask for the settings. The first question builds them.
Step 1 of 10
Nothing yet
Objects: 0
The class is loaded. Its field is empty. No settings object exists.
Step 1: Nothing yet
class ConfigManager: _instance = None @classmethod def get_instance(cls): if cls._instance is None: cls._instance = cls._create() return cls._instanceauth.config = ConfigManager.get_instance()payment.config = ConfigManager.get_instance()analytics.config = ConfigManager.get_instance()- Watch
- The instance field
- Result
- 1 object
The constructor runs once, in step four.
In the real world
The same singleton doing real jobs. Pick one and step through it.
Why volatile is needed: another thread sees the address before the content.
Step 1 of 4
A begins
Creating an object is three steps: get memory, fill it, store the address.
Step 1: A begins
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Check and act without a lock
criticalTwo threads both see the empty field and both build.
Wrongif cls._instance is None: cls._instance = cls()Rightwith cls._lock: if cls._instance is None: cls._instance = cls()No second check
criticalThe thread that waited builds again, with the lock in its hand.
Wrongif cls._instance is None: with cls._lock: cls._instance = cls()Rightif cls._instance is None: with cls._lock: if cls._instance is None: cls._instance = cls()Storing before it is ready
criticalAnother thread skips the lock and uses an empty object.
Wrongcls._instance = object.__new__(cls)cls._instance.load()Rightfresh = object.__new__(cls)fresh.load()cls._instance = fresh__new__ with __init__
majorPython runs __init__ on every call and resets the values.
Wrongdef __new__(cls): return the_onedef __init__(self): self.url = DEFAULTRightthe_one = Config() # at module level# no __new__ neededPer-user data in it
criticalThere is one object and many users. Asha sees the cart of Lee.
WrongCart.get_instance().add(item)Rightcart = carts.of(user)cart.add(item)Fetching it deep inside
majorThe signature hides what the class needs, and tests cannot replace it.
Wrongdef page(self): flags = Flags.get_instance()Rightdef __init__(self, flags): self._flags = flags
Interview tips
Ask first
- Must there be one?
- One per what?
- Who may replace it?
Safe by default
- Java: enum or holder.
- C++: static local.
- Python, TS: a module.
Keep it boring
- Read-only if you can.
- No user data.
- A close for resources.
In an interview
- Write the short one.
- Say what breaks it.
- Offer to pass it in.