Singleton
medium 60 minOne object and one way to reach it.
Watch lesson4:52
When it comes up
The moments this idea belongs in a design interview, and the moments it does not.
Listen
Words that announce it
| You hear | Think | First move |
|---|---|---|
| "There is only one printer" | One per what? | Ask: per process or per building? |
| "All classes need the config" | Shared, read-only | Build in main, pass on |
| "Make the logger global" | Multiton by name | Ask what tests should see |
| "Implement a thread safe singleton" | A coding task | Write holder or checked lock, explain both checks |
| "Only one job may run" | Not this pattern | Lease with a fencing number |
| "One per customer" | Scope | A registry, with removal |
Decide
One question, three answers
In a parking lot exercise the interviewer asks whether ParkingLot should be a Singleton.
BreaksYes, there is only one
- How
- Static getInstance everywhere.
- Limit
- The second lot is the first extension they will ask for, and tests share the lot.
- Choose when
- Not here.
WorksYes, behind an interface
- How
- One access point, classes know the interface.
- Limit
- Still fetched, still shared by tests.
- Choose when
- The interviewer insists on showing the pattern.
StrongNo, main builds one
- How
ParkingLothas a normal constructor. One object exists because main creates one.- Limit
- You must explain it in a sentence.
- Choose when
- Nearly always. Offer to write the Singleton to show that you can.
Bring it up when
- A resource is limited per process
- The value is read-only and needed deep inside a library
- You can say one per what
Stay away when
- It would save you a parameter
- It holds a user's data
- The next requirement could be: two of them
Two minutes that show it
Interviewer
Write a thread safe singleton.
You
In Java I would use an enum: one line, created once by the runtime, safe against serialization. May I also show the checked lock, since you may want to see the reasoning?
Interviewer
Please.
You
First check without lock, for speed. Then the lock, then a second check, because another thread may have built it while I waited. The field is volatile so that nobody sees an unfinished object. And I would not use it for our service: main can build one and pass it on, then tests can replace it.