AlgoViz

Design a parking lot

medium 90 min

Model 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

PatternWhereProtects fromPrice
StrategyPricingA new tariff in ParkingLotOne interface
DecoratorFirstMinutesFree, DailyCap around a ruleA class for every combinationOrder of wrapping matters
Factory (a function)make_pricing(plan)The choice of rule in five placesOne function
FacadeParkingLot for the gatesGates that know pools and pricesNone, it is the class anyway
ObserverSigns, as an extensionSigns inside the lotOrder and slow listeners
Dependency injectionClock, pricing, paymentsUntestable time and cardsA 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}")
A factory is often one function. It reads configuration and is the only place that knows both plans.

Refused

Patterns people add by habit

PatternThe usual reasonWhy 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 vehiclescreateVehicle("car")VehicleType["CAR"] does it, and rejects a typo
State classes for a spaceFree and takenTwo states with one difference. The queue says it
Template methodA bus overrides spotsNeededA 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"); }}
Double-checked locking, and the shorter way. In C++ a static local variable inside a function is safe since C++11. In Python a module already is one.

Principles

SOLID, with one proof each

LetterPrincipleProof in this design
SSingle responsibilityA new tariff does not touch the pool, a new search rule does not touch pricing
OOpen/closedDailyCap was added without opening HourlyPricing or ParkingLot
LLiskov substitutionAny Pricing works in leave: whole cents, never negative, no side effects
IInterface segregationPayments has one method. The lot does not see refunds
DDependency inversionParkingLot 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.