Model ParkingLot with floors of typed spots, issue a Ticket on entry, compute a fee by strategy on exit.
- Requirements: multiple floors, vehicle types (bike, car, truck), spot types, entry/exit gates, hourly pricing, full-lot handling.
- Entities:
ParkingLot, Floor, Spot (type, occupied), Vehicle, Ticket, FeeStrategy, SpotAllocationStrategy (nearest, lowest floor).
- Concurrency: two cars must not get the same spot; use an atomic
tryOccupy() per spot (CAS) or a lock per floor.
- Extensions: EV charging spots, reservations, payment, display boards (Observer).
class Spot {
private final AtomicBoolean taken = new AtomicBoolean();
final SpotType type;
Spot(SpotType t){ type = t; }
boolean tryOccupy(){ return taken.compareAndSet(false, true); }
void free(){ taken.set(false); }
}
class ParkingLot {
Optional<Ticket> park(Vehicle v, Instant now) {
for (Floor f : floors)
for (Spot s : f.spotsFor(v.type()))
if (s.tryOccupy()) return Optional.of(new Ticket(UUID.randomUUID(), v, s, now));
return Optional.empty();
}
}
- Fee:
FeeStrategy.compute(Duration) with hourly slabs; pick via vehicle type.
- Keep free spots in a queue per type for O(1) allocation instead of scanning.
⚠ Follow-up traps
- What if a bike takes a car spot? Define compatibility rules (a car spot accepts bikes only as fallback) in the allocation strategy.
- How do you handle a lost ticket? Look up by plate (index) and charge the max-day fee.
#parking-lot#strategy#factory