Design a parking lot
medium 90 minModel a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.
Watch lesson4:48
Patterns
Which ones, and which ones not
The point: name a pattern only when you can name the change it protects you from.
Used
Patterns that earn their place
| Pattern | Where | Protects from | Price |
|---|---|---|---|
| Strategy | Pricing | A new tariff in ParkingLot | One interface |
| Decorator | FirstMinutesFree, DailyCap around a rule | A class for every combination | Order of wrapping matters |
| Factory (a function) | make_pricing(plan) | The choice of rule in five places | One function |
| Facade | ParkingLot for the gates | Gates that know pools and prices | None, it is the class anyway |
| Observer | Signs, as an extension | Signs inside the lot | Order and slow listeners |
| Dependency injection | Clock, pricing, payments | Untestable time and cards | A longer constructor |
Python
def make_pricing(plan: str) -> Pricing: """The one place that knows which rule a car park uses.""" if plan == "hourly": return HourlyPricing({SpotSize.SMALL: 100, SpotSize.MEDIUM: 200, SpotSize.LARGE: 500}) if plan == "event": return FlatPricing(1500) raise ValueError(f"unknown plan: {plan}")Refused
Patterns people add by habit
| Pattern | The usual reason | Why not here |
|---|---|---|
| Singleton | "Only one lot exists, state must be consistent, access is global" | One instance made in main gives the same. Global access is the problem, not the benefit |
| Factory for vehicles | createVehicle("car") | VehicleType["CAR"] does it, and rejects a typo |
| State classes for a space | Free and taken | Two states with one difference. The queue says it |
| Template method | A bus overrides spotsNeeded | A number is not an algorithm |
If they insist
A Singleton that is at least correct
You may be asked to write one. Know what goes wrong. The lazy version that checks for null, locks and checks again (double-checked locking) needs volatile in Java: without it another thread can see a reference to an object whose constructor has not finished. A lock around every call is correct and slower. Two shorter ways are safe without any of that.
Java
final class LotHolder { private static volatile ParkingLot instance; // volatile: no half-built object static ParkingLot get() { if (instance == null) { // fast path, no lock synchronized (LotHolder.class) { if (instance == null) instance = build(); // someone may have been faster } } return instance; } /* Shorter: the class is loaded on first use, and the JVM loads it once. */ private static final class Lazy { static final ParkingLot LOT = build(); } static ParkingLot simple() { return Lazy.LOT; } private static ParkingLot build() { throw new UnsupportedOperationException("read the configuration here"); }}Principles
SOLID, with one proof each
| Letter | Principle | Proof in this design |
|---|---|---|
| S | Single responsibility | A new tariff does not touch the pool, a new search rule does not touch pricing |
| O | Open/closed | DailyCap was added without opening HourlyPricing or ParkingLot |
| L | Liskov substitution | Any Pricing works in leave: whole cents, never negative, no side effects |
| I | Interface segregation | Payments has one method. The lot does not see refunds |
| D | Dependency inversion | ParkingLot knows Pricing, not HourlyPricing |
Where does the price belong?
BreaksIn the ticket or the vehicle
- How
ticket.price()with an if chain on the vehicle type.- Limit
- Every tariff change opens the record. Tickets in the map follow two rules after a deployment.
- Choose when
- Never.
WorksA method in the lot
- How
ParkingLot._fee(ticket).- Limit
- Fine for one rule. The third rule is an if, and the lot now changes for two reasons.
- Choose when
- A first version in ten minutes. Say that it will move.
StrongA rule that is passed in
- How
Pricing.price_cents(ticket, left_at), wrapped by decorators for free minutes and caps.- Limit
- One more name to learn.
- Choose when
- As soon as marketing is mentioned.