Code Implementation
Implementation Overview
We'll implement the Parking Lot system class by class, following the class diagram we designed. Every class in the diagram becomes a class in code. Every relationship becomes a field reference or inheritance.
Implementation order:
- Enums —
VehicleTypeandSpotType(foundational constants) - Vehicle Hierarchy — Abstract
VehiclewithCar,Truck,Motorcyclesubclasses - ParkingSpot — Core entity with compatibility logic
- Floor — Manages a collection of spots
- PricingStrategy — Interface with
HourlyPricingandFlatRatePricingimplementations - ParkingTicket — Session record linking vehicle, spot, and time
- ParkingLot — Top-level coordinator
- Usage Example — Realistic scenario demonstrating the full system
This order follows the dependency principle: we implement classes with no dependencies first, then classes that depend on them. Enums depend on nothing. Vehicle depends on VehicleType. ParkingSpot depends on Vehicle and SpotType. And so on up to ParkingLot, which depends on everything.
Step 1: Enums — VehicleType and SpotType
Enums define the fixed set of vehicle types and spot sizes. Using enums instead of strings prevents typos and enables compile-time safety — you can't accidentally pass "sedan" when the system expects "CAR". (Fundamentals S3 — Enums)
The VehicleType enum also plays a key role in spot compatibility (FR4).
from enum import Enum
class VehicleType(Enum):
MOTORCYCLE = "MOTORCYCLE"
CAR = "CAR"
TRUCK = "TRUCK"
class SpotType(Enum):
COMPACT = "COMPACT"
REGULAR = "REGULAR"
LARGE = "LARGE"public enum VehicleType {
MOTORCYCLE,
CAR,
TRUCK
}
public enum SpotType {
COMPACT,
REGULAR,
LARGE
}Step 2: Vehicle Hierarchy
The Vehicle abstract class defines shared attributes (licensePlate, type) while concrete subclasses (Car, Truck, Motorcycle) each set their own VehicleType.
This is inheritance in action — all vehicles share the same interface, but each type identifies itself. The ParkingSpot can call vehicle.getType() on any vehicle and get a polymorphic response without knowing the concrete class. (Fundamentals S3 — Polymorphism)
from abc import ABC, abstractmethod
class Vehicle(ABC):
"""Abstract base class for all vehicles in the parking lot."""
def __init__(self, license_plate: str, vehicle_type: VehicleType):
self._license_plate = license_plate
self._type = vehicle_type
def get_type(self) -> VehicleType:
return self._type
def get_license_plate(self) -> str:
return self._license_plate
def __str__(self) -> str:
return f"{self._type.value}({self._license_plate})"
class Car(Vehicle):
def __init__(self, license_plate: str):
super().__init__(license_plate, VehicleType.CAR)
class Truck(Vehicle):
def __init__(self, license_plate: str):
super().__init__(license_plate, VehicleType.TRUCK)
class Motorcycle(Vehicle):
def __init__(self, license_plate: str):
super().__init__(license_plate, VehicleType.MOTORCYCLE)public abstract class Vehicle {
private final String licensePlate;
private final VehicleType type;
protected Vehicle(String licensePlate, VehicleType type) {
this.licensePlate = licensePlate;
this.type = type;
}
public VehicleType getType() {
return type;
}
public String getLicensePlate() {
return licensePlate;
}
@Override
public String toString() {
return type + "(" + licensePlate + ")";
}
}
public class Car extends Vehicle {
public Car(String licensePlate) {
super(licensePlate, VehicleType.CAR);
}
}
public class Truck extends Vehicle {
public Truck(String licensePlate) {
super(licensePlate, VehicleType.TRUCK);
}
}
public class Motorcycle extends Vehicle {
public Motorcycle(String licensePlate) {
super(licensePlate, VehicleType.MOTORCYCLE);
}
}Step 3: ParkingSpot — Compatibility Logic
The ParkingSpot class is where the vehicle-spot compatibility logic lives (FR4). The can_fit_vehicle() method implements the rules:
- COMPACT spots → Motorcycles only
- REGULAR spots → Motorcycles or Cars
- LARGE spots → Any vehicle type
This method is the Information Expert (GRASP from Fundamentals S7) — the spot knows its own type, so it decides whether a vehicle fits.
The park() and unpark() methods manage the spot's occupancy state. Notice that park() validates compatibility before assignment — defense in depth.
class ParkingSpot:
"""A single parking spot with type-based vehicle compatibility."""
# Compatibility map: SpotType -> set of VehicleTypes that can fit
COMPATIBILITY = {
SpotType.COMPACT: {VehicleType.MOTORCYCLE},
SpotType.REGULAR: {VehicleType.MOTORCYCLE, VehicleType.CAR},
SpotType.LARGE: {VehicleType.MOTORCYCLE, VehicleType.CAR, VehicleType.TRUCK},
}
def __init__(self, spot_id: int, spot_type: SpotType):
self._id = spot_id
self._spot_type = spot_type
self._is_occupied = False
self._vehicle: Vehicle | None = None
def can_fit_vehicle(self, vehicle_type: VehicleType) -> bool:
"""Check if a vehicle type is compatible with this spot type."""
return vehicle_type in self.COMPATIBILITY[self._spot_type]
def is_available(self) -> bool:
return not self._is_occupied
def park(self, vehicle: Vehicle) -> None:
"""Park a vehicle in this spot. Raises ValueError if incompatible or occupied."""
if self._is_occupied:
raise ValueError(f"Spot {self._id} is already occupied.")
if not self.can_fit_vehicle(vehicle.get_type()):
raise ValueError(
f"Vehicle type {vehicle.get_type().value} cannot fit in "
f"{self._spot_type.value} spot."
)
self._vehicle = vehicle
self._is_occupied = True
def unpark(self) -> Vehicle:
"""Remove and return the vehicle from this spot."""
if not self._is_occupied:
raise ValueError(f"Spot {self._id} is already empty.")
vehicle = self._vehicle
self._vehicle = None
self._is_occupied = False
return vehicle
@property
def spot_type(self) -> SpotType:
return self._spot_type
@property
def spot_id(self) -> int:
return self._id
def __str__(self) -> str:
status = f"occupied by {self._vehicle}" if self._is_occupied else "available"
return f"Spot({self._id}, {self._spot_type.value}, {status})"import java.util.*;
public class ParkingSpot {
// Compatibility map: which vehicle types fit in which spot types
private static final Map<SpotType, Set<VehicleType>> COMPATIBILITY = Map.of(
SpotType.COMPACT, Set.of(VehicleType.MOTORCYCLE),
SpotType.REGULAR, Set.of(VehicleType.MOTORCYCLE, VehicleType.CAR),
SpotType.LARGE, Set.of(VehicleType.MOTORCYCLE, VehicleType.CAR, VehicleType.TRUCK)
);
private final int id;
private final SpotType spotType;
private boolean isOccupied;
private Vehicle vehicle;
public ParkingSpot(int id, SpotType spotType) {
this.id = id;
this.spotType = spotType;
this.isOccupied = false;
this.vehicle = null;
}
public boolean canFitVehicle(VehicleType vehicleType) {
return COMPATIBILITY.get(spotType).contains(vehicleType);
}
public static boolean canVehicleFitInSpotType(VehicleType vehicleType, SpotType spotType) {
return COMPATIBILITY.get(spotType).contains(vehicleType);
}
public boolean isAvailable() {
return !isOccupied;
}
public void park(Vehicle vehicle) {
if (isOccupied) {
throw new IllegalStateException("Spot " + id + " is already occupied.");
}
if (!canFitVehicle(vehicle.getType())) {
throw new IllegalArgumentException(
"Vehicle type " + vehicle.getType() + " cannot fit in " + spotType + " spot."
);
}
this.vehicle = vehicle;
this.isOccupied = true;
}
public Vehicle unpark() {
if (!isOccupied) {
throw new IllegalStateException("Spot " + id + " is already empty.");
}
Vehicle parkedVehicle = this.vehicle;
this.vehicle = null;
this.isOccupied = false;
return parkedVehicle;
}
public SpotType getSpotType() { return spotType; }
public int getId() { return id; }
@Override
public String toString() {
String status = isOccupied ? "occupied by " + vehicle : "available";
return "Spot(" + id + ", " + spotType + ", " + status + ")";
}
}Step 4: Floor — Spot Management
The Floor class manages a collection of ParkingSpot objects. Its primary responsibility is finding an available spot that's compatible with a given vehicle type.
Notice that Floor doesn't know anything about vehicles, tickets, or pricing — it only manages spots. This is SRP in action (Fundamentals S6). The Floor delegates compatibility checking to ParkingSpot.can_fit_vehicle() rather than re-implementing the logic.
from typing import Optional
class Floor:
"""A single floor in the parking lot, containing multiple spots."""
def __init__(self, floor_number: int, spots: list[ParkingSpot]):
self._floor_number = floor_number
self._spots = spots
def find_available_spot(self, vehicle_type: VehicleType) -> Optional[ParkingSpot]:
"""Find the first available spot that can fit the given vehicle type."""
for spot in self._spots:
if spot.is_available() and spot.can_fit_vehicle(vehicle_type):
return spot
return None
def get_available_spot_count(self, spot_type: SpotType) -> int:
"""Count available spots of a specific type on this floor."""
return sum(
1 for spot in self._spots
if spot.spot_type == spot_type and spot.is_available()
)
@property
def floor_number(self) -> int:
return self._floor_number
def __str__(self) -> str:
available = sum(1 for s in self._spots if s.is_available())
return f"Floor({self._floor_number}, {available}/{len(self._spots)} available)"import java.util.List;
public class Floor {
private final int floorNumber;
private final List<ParkingSpot> spots;
public Floor(int floorNumber, List<ParkingSpot> spots) {
this.floorNumber = floorNumber;
this.spots = spots;
}
public ParkingSpot findAvailableSpot(VehicleType vehicleType) {
for (ParkingSpot spot : spots) {
if (spot.isAvailable() && spot.canFitVehicle(vehicleType)) {
return spot;
}
}
return null;
}
public int getAvailableSpotCount(SpotType spotType) {
int count = 0;
for (ParkingSpot spot : spots) {
if (spot.getSpotType() == spotType && spot.isAvailable()) {
count++;
}
}
return count;
}
public int getFloorNumber() { return floorNumber; }
@Override
public String toString() {
long available = spots.stream().filter(ParkingSpot::isAvailable).count();
return "Floor(" + floorNumber + ", " + available + "/" + spots.size() + " available)";
}
}Step 5: PricingStrategy — Strategy Pattern
The PricingStrategy interface defines a single method: calculateFee(duration). Concrete implementations provide different algorithms.
This is the Strategy Pattern (Fundamentals S12) — the ParkingLot holds a reference to a PricingStrategy and calls calculateFee() without knowing which algorithm runs. We can add DynamicSurgePricing, WeekendPricing, or any other model by creating a new class — the ParkingLot never changes. This satisfies the Open/Closed Principle (Fundamentals S6).
from abc import ABC, abstractmethod
from datetime import timedelta
import math
class PricingStrategy(ABC):
"""Interface for parking fee calculation algorithms."""
@abstractmethod
def calculate_fee(self, duration: timedelta) -> float:
"""Calculate the parking fee for the given duration."""
pass
class HourlyPricing(PricingStrategy):
"""Charges per hour (or fraction thereof)."""
def __init__(self, hourly_rate: float):
self._hourly_rate = hourly_rate
def calculate_fee(self, duration: timedelta) -> float:
# Round up to the next full hour
hours = math.ceil(duration.total_seconds() / 3600)
return hours * self._hourly_rate
class FlatRatePricing(PricingStrategy):
"""Charges a fixed rate regardless of duration."""
def __init__(self, flat_rate: float):
self._flat_rate = flat_rate
def calculate_fee(self, duration: timedelta) -> float:
return self._flat_rateimport java.time.Duration;
public interface PricingStrategy {
double calculateFee(Duration duration);
}
public class HourlyPricing implements PricingStrategy {
private final double hourlyRate;
public HourlyPricing(double hourlyRate) {
this.hourlyRate = hourlyRate;
}
@Override
public double calculateFee(Duration duration) {
// Round up to the next full hour
long hours = (long) Math.ceil(duration.toSeconds() / 3600.0);
return hours * hourlyRate;
}
}
public class FlatRatePricing implements PricingStrategy {
private final double flatRate;
public FlatRatePricing(double flatRate) {
this.flatRate = flatRate;
}
@Override
public double calculateFee(Duration duration) {
return flatRate;
}
}Step 6: ParkingTicket — Session Record
The ParkingTicket captures the parking session: which vehicle parked in which spot at what time. It's created on entry and used to calculate the fee on exit.
The ticket ID is auto-generated using a UUID to ensure uniqueness across the system.
import uuid
from datetime import datetime
class ParkingTicket:
"""Records a parking session — vehicle, spot, and entry time."""
def __init__(self, vehicle: Vehicle, spot: ParkingSpot):
self._ticket_id = str(uuid.uuid4())[:8] # Short unique ID
self._vehicle = vehicle
self._spot = spot
self._entry_time = datetime.now()
@property
def ticket_id(self) -> str:
return self._ticket_id
@property
def vehicle(self) -> Vehicle:
return self._vehicle
@property
def spot(self) -> ParkingSpot:
return self._spot
@property
def entry_time(self) -> datetime:
return self._entry_time
def __str__(self) -> str:
return (
f"Ticket({self._ticket_id}, {self._vehicle}, "
f"Spot {self._spot.spot_id}, entered at {self._entry_time:%H:%M})"
)import java.time.LocalDateTime;
import java.util.UUID;
public class ParkingTicket {
private final String ticketId;
private final Vehicle vehicle;
private final ParkingSpot spot;
private final LocalDateTime entryTime;
public ParkingTicket(Vehicle vehicle, ParkingSpot spot) {
this.ticketId = UUID.randomUUID().toString().substring(0, 8);
this.vehicle = vehicle;
this.spot = spot;
this.entryTime = LocalDateTime.now();
}
public String getTicketId() { return ticketId; }
public Vehicle getVehicle() { return vehicle; }
public ParkingSpot getSpot() { return spot; }
public LocalDateTime getEntryTime() { return entryTime; }
@Override
public String toString() {
return "Ticket(" + ticketId + ", " + vehicle + ", Spot " +
spot.getId() + ", entered at " + entryTime.toLocalTime() + ")";
}
}Step 7: ParkingLot — The Coordinator
The ParkingLot class is the top-level facade. It exposes high-level operations (parkVehicle, unparkVehicle) and delegates work to internal classes:
- Spot search →
Floor.findAvailableSpot() - Compatibility check →
ParkingSpot.canFitVehicle() - Fee calculation →
PricingStrategy.calculateFee()
This delegation pattern keeps ParkingLot focused on coordination (SRP) while each helper class handles its own responsibility. The ParkingLot is also the entry point for the Admin actor (setting pricing strategy, viewing capacity).
Notice the activeTickets dictionary — it maps ticket IDs to tickets for O(1) lookup on exit.
from datetime import datetime
class ParkingLot:
"""Multi-floor parking lot with pluggable pricing."""
def __init__(self, name: str, pricing_strategy: PricingStrategy):
self._name = name
self._floors: list[Floor] = []
self._pricing_strategy = pricing_strategy
self._active_tickets: dict[str, ParkingTicket] = {}
def add_floor(self, floor: Floor) -> None:
"""Add a floor to the parking lot."""
self._floors.append(floor)
def set_pricing_strategy(self, strategy: PricingStrategy) -> None:
"""Swap the pricing strategy at runtime (Strategy Pattern)."""
self._pricing_strategy = strategy
def park_vehicle(self, vehicle: Vehicle) -> ParkingTicket:
"""Park a vehicle: find a compatible spot, assign it, and return a ticket."""
vehicle_type = vehicle.get_type()
# Search floors for an available compatible spot
for floor in self._floors:
spot = floor.find_available_spot(vehicle_type)
if spot is not None:
spot.park(vehicle)
ticket = ParkingTicket(vehicle, spot)
self._active_tickets[ticket.ticket_id] = ticket
print(
f"Parked {vehicle} in Spot {spot.spot_id} "
f"on Floor {floor.floor_number}. "
f"Ticket: {ticket.ticket_id}"
)
return ticket
raise ValueError(
f"No available spot for vehicle type {vehicle_type.value}. "
f"Parking lot is full for this type."
)
def unpark_vehicle(self, ticket_id: str) -> float:
"""Unpark a vehicle: calculate fee, release spot, and return the fee."""
if ticket_id not in self._active_tickets:
raise ValueError(f"Invalid ticket ID: {ticket_id}")
ticket = self._active_tickets.pop(ticket_id)
exit_time = datetime.now()
duration = exit_time - ticket.entry_time
# Calculate fee using the active pricing strategy
fee = self._pricing_strategy.calculate_fee(duration)
# Release the spot
ticket.spot.unpark()
print(
f"Unparked {ticket.vehicle} from Spot {ticket.spot.spot_id}. "
f"Duration: {duration}. Fee: ${fee:.2f}"
)
return fee
def get_available_spots(self, vehicle_type: VehicleType) -> int:
"""Count total available spots compatible with the given vehicle type."""
count = 0
for floor in self._floors:
for spot_type in SpotType:
# Check if this spot type can fit the vehicle type
if vehicle_type in ParkingSpot.COMPATIBILITY.get(spot_type, set()):
count += floor.get_available_spot_count(spot_type)
return count
def __str__(self) -> str:
total_active = len(self._active_tickets)
return f"ParkingLot({self._name}, {len(self._floors)} floors, {total_active} active tickets)"import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
public class ParkingLot {
private final String name;
private final List<Floor> floors;
private PricingStrategy pricingStrategy;
private final Map<String, ParkingTicket> activeTickets;
public ParkingLot(String name, PricingStrategy pricingStrategy) {
this.name = name;
this.floors = new ArrayList<>();
this.pricingStrategy = pricingStrategy;
this.activeTickets = new HashMap<>();
}
public void addFloor(Floor floor) {
floors.add(floor);
}
public void setPricingStrategy(PricingStrategy strategy) {
this.pricingStrategy = strategy;
}
public ParkingTicket parkVehicle(Vehicle vehicle) {
VehicleType vehicleType = vehicle.getType();
for (Floor floor : floors) {
ParkingSpot spot = floor.findAvailableSpot(vehicleType);
if (spot != null) {
spot.park(vehicle);
ParkingTicket ticket = new ParkingTicket(vehicle, spot);
activeTickets.put(ticket.getTicketId(), ticket);
System.out.println(
"Parked " + vehicle + " in Spot " + spot.getId() +
" on Floor " + floor.getFloorNumber() +
". Ticket: " + ticket.getTicketId()
);
return ticket;
}
}
throw new IllegalStateException(
"No available spot for vehicle type " + vehicleType +
". Parking lot is full for this type."
);
}
public double unparkVehicle(String ticketId) {
ParkingTicket ticket = activeTickets.remove(ticketId);
if (ticket == null) {
throw new IllegalArgumentException("Invalid ticket ID: " + ticketId);
}
LocalDateTime exitTime = LocalDateTime.now();
Duration duration = Duration.between(ticket.getEntryTime(), exitTime);
double fee = pricingStrategy.calculateFee(duration);
ticket.getSpot().unpark();
System.out.println(
"Unparked " + ticket.getVehicle() + " from Spot " +
ticket.getSpot().getId() + ". Fee: $" + String.format("%.2f", fee)
);
return fee;
}
public int getAvailableSpots(VehicleType vehicleType) {
int count = 0;
for (Floor floor : floors) {
for (SpotType spotType : SpotType.values()) {
// Check compatibility using ParkingSpot's static map
if (ParkingSpot.canVehicleFitInSpotType(vehicleType, spotType)) {
count += floor.getAvailableSpotCount(spotType);
}
}
}
return count;
}
}Step 8: Usage Example — Putting It All Together
Let's see the complete system in action with a realistic scenario: a 2-floor parking lot that handles multiple vehicles, demonstrates spot compatibility, and swaps pricing strategies.
from datetime import timedelta
def main():
# --- Setup: Create a 2-floor parking lot ---
hourly_pricing = HourlyPricing(hourly_rate=5.0)
lot = ParkingLot("Downtown Garage", hourly_pricing)
# Floor 1: 2 compact, 2 regular, 1 large
floor1_spots = [
ParkingSpot(1, SpotType.COMPACT),
ParkingSpot(2, SpotType.COMPACT),
ParkingSpot(3, SpotType.REGULAR),
ParkingSpot(4, SpotType.REGULAR),
ParkingSpot(5, SpotType.LARGE),
]
lot.add_floor(Floor(1, floor1_spots))
# Floor 2: 1 compact, 2 regular, 2 large
floor2_spots = [
ParkingSpot(6, SpotType.COMPACT),
ParkingSpot(7, SpotType.REGULAR),
ParkingSpot(8, SpotType.REGULAR),
ParkingSpot(9, SpotType.LARGE),
ParkingSpot(10, SpotType.LARGE),
]
lot.add_floor(Floor(2, floor2_spots))
print(f"=== {lot} ===")
print(f"Available spots for CAR: {lot.get_available_spots(VehicleType.CAR)}")
print(f"Available spots for TRUCK: {lot.get_available_spots(VehicleType.TRUCK)}")
print(f"Available spots for MOTORCYCLE: {lot.get_available_spots(VehicleType.MOTORCYCLE)}")
# --- Park some vehicles ---
car1 = Car("ABC-1234")
motorcycle1 = Motorcycle("MTR-5678")
truck1 = Truck("TRK-9012")
ticket_car1 = lot.park_vehicle(car1) # Gets a Regular or Large spot
ticket_moto1 = lot.park_vehicle(motorcycle1) # Gets a Compact spot (smallest available)
ticket_truck1 = lot.park_vehicle(truck1) # Gets a Large spot (only option for trucks)
print(f"\nAfter parking 3 vehicles:")
print(f"Available spots for CAR: {lot.get_available_spots(VehicleType.CAR)}")
print(f"Available spots for TRUCK: {lot.get_available_spots(VehicleType.TRUCK)}")
# --- Unpark the car right away: a stay under an hour rounds up to 1 hour, $5.00 ---
# (a 3-hour stay would be HourlyPricing at $5/hour × 3 = $15.00)
fee = lot.unpark_vehicle(ticket_car1.ticket_id)
print(f"\nCar parking fee: ${fee:.2f}")
# --- Swap to flat-rate pricing and unpark the truck ---
lot.set_pricing_strategy(FlatRatePricing(flat_rate=20.0))
fee = lot.unpark_vehicle(ticket_truck1.ticket_id)
print(f"Truck parking fee (flat rate): ${fee:.2f}")
print(f"\n=== After unparking: {lot} ===")
if __name__ == "__main__":
main()import java.util.*;
public class ParkingLotDemo {
public static void main(String[] args) {
// --- Setup: Create a 2-floor parking lot ---
PricingStrategy hourlyPricing = new HourlyPricing(5.0);
ParkingLot lot = new ParkingLot("Downtown Garage", hourlyPricing);
// Floor 1: 2 compact, 2 regular, 1 large
List<ParkingSpot> floor1Spots = List.of(
new ParkingSpot(1, SpotType.COMPACT),
new ParkingSpot(2, SpotType.COMPACT),
new ParkingSpot(3, SpotType.REGULAR),
new ParkingSpot(4, SpotType.REGULAR),
new ParkingSpot(5, SpotType.LARGE)
);
lot.addFloor(new Floor(1, new ArrayList<>(floor1Spots)));
// Floor 2: 1 compact, 2 regular, 2 large
List<ParkingSpot> floor2Spots = List.of(
new ParkingSpot(6, SpotType.COMPACT),
new ParkingSpot(7, SpotType.REGULAR),
new ParkingSpot(8, SpotType.REGULAR),
new ParkingSpot(9, SpotType.LARGE),
new ParkingSpot(10, SpotType.LARGE)
);
lot.addFloor(new Floor(2, new ArrayList<>(floor2Spots)));
System.out.println("=== Parking Lot Setup ===");
System.out.println("Available for CAR: " + lot.getAvailableSpots(VehicleType.CAR));
System.out.println("Available for TRUCK: " + lot.getAvailableSpots(VehicleType.TRUCK));
System.out.println("Available for MOTORCYCLE: " + lot.getAvailableSpots(VehicleType.MOTORCYCLE));
// --- Park some vehicles ---
Vehicle car1 = new Car("ABC-1234");
Vehicle motorcycle1 = new Motorcycle("MTR-5678");
Vehicle truck1 = new Truck("TRK-9012");
ParkingTicket ticketCar = lot.parkVehicle(car1);
ParkingTicket ticketMoto = lot.parkVehicle(motorcycle1);
ParkingTicket ticketTruck = lot.parkVehicle(truck1);
System.out.println("\nAfter parking 3 vehicles:");
System.out.println("Available for CAR: " + lot.getAvailableSpots(VehicleType.CAR));
System.out.println("Available for TRUCK: " + lot.getAvailableSpots(VehicleType.TRUCK));
// --- Unpark the car ---
double fee = lot.unparkVehicle(ticketCar.getTicketId());
System.out.println("Car parking fee: $" + String.format("%.2f", fee));
// --- Swap to flat-rate pricing and unpark the truck ---
lot.setPricingStrategy(new FlatRatePricing(20.0));
fee = lot.unparkVehicle(ticketTruck.getTicketId());
System.out.println("Truck fee (flat rate): $" + String.format("%.2f", fee));
System.out.println("\n=== Final State ===");
}
}What this example demonstrates:
- Vehicle-Spot Compatibility — The motorcycle gets a compact spot, the car gets a regular spot, the truck gets a large spot. Each vehicle takes the first free spot that fits it; because each floor lists its spots from compact to large, here that is the smallest compatible type.
- Strategy Pattern in Action — We start with hourly pricing ($5/hour), unpark the car with that pricing, then swap to flat-rate pricing ($20) before unparking the truck. The
unparkVehicle()method doesn't change — it callspricingStrategy.calculateFee()polymorphically. - Capacity Tracking — We check available spots before and after parking to verify counts change correctly.
- Ticket-Based Identification — Each vehicle is tracked by its ticket ID, not by the vehicle or spot directly. This decouples the parking session from the physical objects.