Design Example: Car Rental System
A Car Rental System (like Hertz or Zipcar) manages vehicle inventory, customer memberships, and the lifecycle of reservations.
Step 1: Requirements Gathering
Core Use Cases:
- Search: Users can search for available cars by location, date, and category (SUV, Sedan, Luxury).
- Reservation: Users can book a car for a specific duration.
- Pick-up/Return: Handle the physical handoff and return of the vehicle.
- Billing: Calculate costs based on duration, fuel level, and damages.
- Inventory Management: Admins can add/remove cars or update their status.
Vehicle States:
- Status: AVAILABLE, RESERVED, LOANED, BEING_SERVICED, LOST.
Step 2: Identify Core Objects
- Vehicle: Abstract base for different car types.
- VehicleLog: Record of a car's history (service, cleanup).
- Account: User (Customer) and Employee (Attendant).
- Reservation: Connects a User to a Vehicle for a specific period.
- Bill: Handles payment calculations and extra charges.
- Location: Specific rental office where cars are stored.
Step 3: Design Class Diagram
Step 4: Implementation in TypeScript
enum VehicleStatus { AVAILABLE, RESERVED, LOANED }
abstract class Vehicle {
constructor(
public licensePlate: string,
public dailyRate: number,
public status: VehicleStatus = VehicleStatus.AVAILABLE
) {}
}
class SUV extends Vehicle {
constructor(licensePlate: string) {
super(licensePlate, 100);
}
}
class Reservation {
constructor(
public id: string,
public user: string,
public vehicle: Vehicle,
public start: Date,
public end: Date
) {}
public getDurationInDays(): number {
return (this.end.getTime() - this.start.getTime()) / (1000 * 3600 * 24);
}
}
class Bill {
public static calculate(reservation: Reservation): number {
const days = reservation.getDurationInDays();
return days * reservation.vehicle.dailyRate;
}
}Deep Dive: Handling Dynamic Fleet Management
Using Composition for vehicle features (GPS, Child Seat) instead of inheritance allows the rental system to add/remove add-ons without creating complex class hierarchies.
Wrap Up
Designing a Car Rental System highlights the need for Atomic Reservations. Ensuring that a vehicle is not overbooked across overlapping dates is the primary technical challenge in the LLD of this system.
[!TIP] Use the Strategy Pattern for dynamic insurance pricing based on the user's age or location.