1. Design Parking Lot
Difficulty: Medium Topics: Object-Oriented Design, Singleton, Factory Pattern, Strategy Pattern Key Concepts: Managing shared resources, pricing logic, concurrency.
Phase 1: Requirements Gathering
Goals
Understand the scope: A multi-level parking lot for different vehicle types.
Identify users: Customers, Parking Attendant/System, Admin.
Define core features (Must-have vs Should-have).
1. Who are the actors?
Customer: Arrives with a vehicle, parks, and pays the fee.
System/Attendant: Issues tickets, assigns spots, calculates fees.
Admin: Manages parking lot capacity, rates, and maintenance (optional).
2. What are the must-have features? (Core)
Multi-Level Parking: Support multiple floors.
Spot Assignment: Find the nearest available spot for a specific vehicle type.
Ticket Generation: Issue a ticket with entry time upon arrival.
Fee Calculation: Calculate parking fee upon exit based on duration.
Payment: Process payment and release the spot.
3. What are the constraints?
Concurrency: Multiple vehicles arriving/exiting simultaneously.
Capacity: Limited spots per floor and type (Compact, Large, Motorcycle).
Scalability: Extensible for new vehicle types or pricing strategies.
Phase 2: Use Cases
UC1: Park Vehicle
Actor: Customer / System Flow:
Vehicle arrives at the entry gate.
System identifies vehicle type (Car, Truck, Motorcycle).
System checks for the nearest available spot of that type.
If full, display "Full".
If available, system occupies the spot and generates a
TicketwithticketIdandentryTime.Gate opens.
UC2: Exit & Pay
Actor: Customer / System Flow:
Customer arrives at the exit gate with
Ticket.System reads the ticket and calculates duration (Current Time - Entry Time).
System calculates fee using the current
PricingStrategy.Customer pays the amount.
System releases the spot (marks it free).
Gate opens.
Phase 3: Class Diagram
Step 1: Core Entities
ParkingLot: Singleton manager.
Level: Represents a floor.
ParkingSpot: An individual slot.
Vehicle: Abstract base class (Car, Truck, Motorcycle).
Ticket: Proof of entry.
PricingStrategy: Logic for fee calculation.
Step 2: Relationships
ParkingLothas-manyLevel(Composition).Levelhas-manyParkingSpot(Composition).ParkingSpothas-aVehicle(Association/Aggregation).TicketreferencesParkingSpotandVehicle.Vehicleis a base class forCar,Truck,Motorcycle(Inheritance).
UML Diagram
Phase 4: Design Patterns
1. Singleton Pattern
Description: Ensures a class has only one instance and provides a global point of access to it.
Why used: The
ParkingLotsystem needs a central point of control for managing shared resources (spots, levels) to prevent conflicting assignments and ensure consistent state across the system.
2. Factory Pattern
Description: A creational pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
Why used: Encapsulates the logic of creating different
Vehicletypes (Car,Truck,Motorcycle). Allows adding new vehicle types without modifying client code.
3. Strategy Pattern
Description: Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Why used: Pricing logic matches this perfectly (
HourlyStrategy,FlatRateStrategy). We can swap pricing models dynamically (e.g., weekend rates) without changing theParkingLotclass.
Phase 5: Code Key Methods
Java Implementation
Phase 6: Discussion
Concurrency
Q: How do we handle multiple entrances simultaneously (SDE-3 Concept)?
Single Node: Instead of using global
synchronizedblocks which create a bottleneck, useReentrantReadWriteLock. Finding an available spot involves many READ operations, while actually parking involves a single WRITE operation. ReadWrite locks allow multiple concurrent readers but exclusive writers. For even higher throughput, useConcurrentHashMapto trackfreeSpotsperSpotType.Distributed System: If the parking lot spans multiple nodes (e.g., massive airport parking managed by microservices), use Distributed Locking (e.g., Redis Redlock or ZooKeeper) on a specific spot before occupying it to prevent double-booking across servers.
Extensibility
Q: How to add electric vehicle charging?
Create a
ElectricSpotextendingParkingSpot.Add
Chargeableinterface toElectricCar.
Pricing Flexibility
Q: How to implement dynamic pricing?
Use the Strategy Pattern. Pass a
PricingStrategy(e.g.,WeekendStrategy,HourlyStrategy) to the calculator method.
SOLID Principles Checklist
S (Single Responsibility):
ParkingSpotmanages state,Ticketmanages session,Levelfinds spots. Separation is clear.O (Open/Closed): New
Vehicletypes can be added by extendingVehicleclass without modifying existing logic significantly.L (Liskov Substitution):
Car,Truckcan be substituted forVehicle.I (Interface Segregation): Interfaces (like
PricingStrategyif implemented) should be focused.D (Dependency Inversion): High-level modules should depend on abstractions (e.g.,
Vehicle) rather than concrete classes.
Last updated