-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCarRentalSystem.java
More file actions
337 lines (283 loc) · 13.9 KB
/
Copy pathCarRentalSystem.java
File metadata and controls
337 lines (283 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
/**
* ============================================================================
* ULTIMATE CAR RENTAL SYSTEM LOW-LEVEL DESIGN (PRODUCTION READY)
* ============================================================================
* INTERVIEW SCRIPT / INTRODUCTION:
* "To design a highly scalable and thread-safe Car Rental System, I am focusing
* on concurrency and the Open/Closed Principle. I will use 4 main patterns:
* 1. STATE PATTERN: To handle the strict lifecycle of a reservation (Pending -> Confirmed).
* 2. STRATEGY PATTERN: To decouple pricing and payments so business rules can change easily.
* 3. DECORATOR PATTERN: To handle add-ons (like GPS or Insurance) without Class Explosion.
* 4. FINE-GRAINED LOCKING: Using ReentrantLocks per vehicle to prevent double-booking
* without freezing the entire branch database."
* ============================================================================
*/
// ==========================================
// 1. STATE MANAGEMENT & ENTITIES
// ==========================================
/*
* INTERVIEW EXPLANATION:
* "I use Enums here for Vehicle Type and Status. If we used standard Strings, a typo
* like 'available' vs 'AVAILABLE' could break our search algorithms. Enums guarantee
* strict type safety at compile time."
*/
enum VehicleType { ECONOMY, SUV, LUXURY }
enum VehicleStatus { AVAILABLE, MAINTENANCE }
/* * INTERVIEW EXPLANATION:
* "This represents a strict State Machine for the Reservation. A booking ALWAYS starts
* as PENDING. We hold the lock on the vehicle, attempt to charge the user's credit card,
* and ONLY if the payment gateway returns 'true' do we transition to CONFIRMED.
* If payment fails, it transitions to CANCELED and the vehicle is instantly freed."
*/
enum ReservationStatus { PENDING, CONFIRMED, CANCELED }
class User {
private String userId;
private String fullName;
// "Capturing driving license is a strict domain requirement for a car rental."
private String drivingLicense;
public User(String userId, String fullName, String drivingLicense) {
this.userId = userId;
this.fullName = fullName;
this.drivingLicense = drivingLicense;
}
public String getUserId() { return userId; }
public String getDrivingLicense() { return drivingLicense; }
}
class Vehicle {
private String licensePlate;
private VehicleType type;
private VehicleStatus status;
private double baseDailyRate;
public Vehicle(String licensePlate, VehicleType type, double baseDailyRate) {
this.licensePlate = licensePlate;
this.type = type;
this.baseDailyRate = baseDailyRate;
this.status = VehicleStatus.AVAILABLE;
}
public String getLicensePlate() { return licensePlate; }
public VehicleStatus getStatus() { return status; }
public double getBaseDailyRate() { return baseDailyRate; }
}
class Reservation {
private String reservationId;
private User user;
private String licensePlate;
private LocalDate startDate;
private LocalDate endDate;
private ReservationStatus status;
public Reservation(User user, String licensePlate, LocalDate startDate, LocalDate endDate) {
this.reservationId = UUID.randomUUID().toString();
this.user = user;
this.licensePlate = licensePlate;
this.startDate = startDate;
this.endDate = endDate;
// "Every reservation must start as PENDING until money physically changes hands."
this.status = ReservationStatus.PENDING;
}
public LocalDate getStartDate() { return startDate; }
public LocalDate getEndDate() { return endDate; }
public ReservationStatus getStatus() { return status; }
public void setStatus(ReservationStatus status) { this.status = status; }
}
// ==========================================
// 2. STRATEGY PATTERNS (Pricing & Payment)
// ==========================================
/* * INTERVIEW EXPLANATION:
* "To adhere to the Open/Closed Principle, I decoupled pricing and payments
* using the Strategy Pattern. If the business introduces a 'Holiday Surge' price
* or integrates 'Apple Pay' tomorrow, we do not need to touch the core checkout logic.
* We just inject a new Strategy class."
*/
interface PricingStrategy {
double calculateBasePrice(Vehicle vehicle, long days);
}
class WeeklyDiscountPricingStrategy implements PricingStrategy {
@Override
public double calculateBasePrice(Vehicle vehicle, long days) {
double total = vehicle.getBaseDailyRate() * days;
// "A simple business rule: 20% discount if you book for a week or more."
return days >= 7 ? total * 0.8 : total;
}
}
interface PaymentStrategy {
boolean processPayment(double amount);
}
class CreditCardPayment implements PaymentStrategy {
@Override
public boolean processPayment(double amount) {
System.out.println("Charging $" + amount + " to Credit Card...");
return true; // "Mocking a successful bank charge for the simulation."
}
}
// ==========================================
// 3. DECORATOR PATTERN (Add-ons)
// ==========================================
/* * INTERVIEW BONUS POINT (AVOIDING CLASS EXPLOSION):
* "I use the Decorator pattern for Add-ons like GPS or Insurance. If I used inheritance,
* I would have to create `CarWithGPS`, `CarWithInsurance`, and `CarWithGPSAndInsurance` classes.
* That is called Class Explosion. The Decorator acts like a wrapper around the base invoice,
* allowing us to stack as many add-ons as we want dynamically at runtime."
*/
interface Invoice { double getTotal(); }
class BaseInvoice implements Invoice {
private double baseAmount;
public BaseInvoice(double baseAmount) { this.baseAmount = baseAmount; }
@Override public double getTotal() { return baseAmount; }
}
abstract class InvoiceDecorator implements Invoice {
protected Invoice wrappedInvoice;
public InvoiceDecorator(Invoice invoice) { this.wrappedInvoice = invoice; }
}
class GPSDecorator extends InvoiceDecorator {
private long days;
public GPSDecorator(Invoice invoice, long days) {
super(invoice);
this.days = days;
}
@Override
public double getTotal() {
// "It calculates the GPS cost ($5/day) and adds it to whatever invoice is inside it."
return wrappedInvoice.getTotal() + (5.0 * days);
}
}
// ==========================================
// 4. CONCURRENT ENGINE (The Double-Booking Fix)
// ==========================================
/* * INTERVIEW EXPLANATION:
* "This is the core of our system's thread safety. If two users try to book the exact
* same car for the exact same dates at the exact same millisecond, a standard system
* will double-book it. I am using ConcurrentHashMaps and ReentrantLocks mapped by
* License Plate to guarantee absolute data integrity."
*/
class Branch {
// "ConcurrentHashMap guarantees O(1) thread-safe lookups across multiple threads."
private Map<String, Vehicle> fleet = new ConcurrentHashMap<>();
/*
* INTERVIEW BONUS POINT:
* "I am using a CopyOnWriteArrayList for the schedules. In a highly concurrent environment
* where many users are reading the schedule to see if a car is free, but only a few
* are writing to it (booking), this structure prevents ConcurrentModificationExceptions."
*/
private Map<String, List<Reservation>> vehicleSchedules = new ConcurrentHashMap<>();
// "Stores a unique physical lock for every single car in the fleet."
private Map<String, ReentrantLock> vehicleLocks = new ConcurrentHashMap<>();
public void addVehicle(Vehicle v) {
fleet.put(v.getLicensePlate(), v);
vehicleSchedules.put(v.getLicensePlate(), new CopyOnWriteArrayList<>());
}
public Vehicle getVehicle(String licensePlate) { return fleet.get(licensePlate); }
// "Helper method to verify date overlaps."
private boolean isVehicleFreeForDates(String licensePlate, LocalDate start, LocalDate end) {
for (Reservation r : vehicleSchedules.get(licensePlate)) {
// "We only check against active/pending reservations. Canceled ones are ignored."
if (r.getStatus() != ReservationStatus.CANCELED &&
!start.isAfter(r.getEndDate()) && !end.isBefore(r.getStartDate())) {
return false; // Collision found! The car is busy.
}
}
return true;
}
/*
* INTERVIEW EXPLANATION (FINE-GRAINED LOCKING):
* "Instead of locking the entire Branch (which would mean only 1 person in the
* world could book a car at a time), I lock ONLY the specific vehicle being requested.
* This is called fine-grained locking and it allows massive system throughput."
*/
public Reservation acquireLockAndReserve(String licensePlate, User user, LocalDate start, LocalDate end) throws Exception {
Vehicle v = fleet.get(licensePlate);
if (v == null || v.getStatus() != VehicleStatus.AVAILABLE) throw new Exception("Car is in maintenance.");
// "Dynamically fetch or create a lock for this specific license plate."
ReentrantLock lock = vehicleLocks.computeIfAbsent(licensePlate, k -> new ReentrantLock());
lock.lock(); // CRITICAL SECTION STARTS HERE
try {
// "We MUST check if the car is free INSIDE the lock. If we checked outside,
// another thread could have snuck in and booked it right before we locked."
if (!isVehicleFreeForDates(licensePlate, start, end)) {
throw new Exception("Date collision: Car was just booked for those dates.");
}
// "Create the reservation and add it to the schedule safely."
Reservation res = new Reservation(user, licensePlate, start, end);
vehicleSchedules.get(licensePlate).add(res);
return res; // Returns securely in the PENDING state
} finally {
// "Crucial: We MUST unlock inside a 'finally' block. If the code above threw
// an error and we didn't unlock here, this car would be permanently frozen forever!"
lock.unlock();
}
}
}
// ==========================================
// 5. GLOBAL ORCHESTRATOR & MAIN
// ==========================================
/*
* INTERVIEW EXPLANATION:
* "The CarRentalSystem is a Singleton. It acts as the Facade for our backend.
* The mobile app or website only ever talks to this class. It orchestrates the
* validation, locking, pricing, and payment flow."
*/
class CarRentalSystem {
private static final CarRentalSystem INSTANCE = new CarRentalSystem();
private CarRentalSystem() {}
public static CarRentalSystem getInstance() { return INSTANCE; }
public void checkout(Branch branch, String licensePlate, User user,
LocalDate start, LocalDate end,
PricingStrategy pricing, PaymentStrategy payment, boolean addGps) {
try {
// 1. Domain Validation
if (user.getDrivingLicense() == null) throw new Exception("Invalid Driving License.");
// 2. Thread-Safe Booking (Creates a PENDING reservation)
Reservation res = branch.acquireLockAndReserve(licensePlate, user, start, end);
Vehicle vehicle = branch.getVehicle(licensePlate);
// Calculate rental duration
long days = ChronoUnit.DAYS.between(start, end);
if (days == 0) days = 1; // Minimum 1 day charge
// 3. Strategy Pattern: Calculate Base Price
double baseCost = pricing.calculateBasePrice(vehicle, days);
Invoice finalInvoice = new BaseInvoice(baseCost);
// 4. Decorator Pattern: Wrap the invoice with Add-ons if requested
if (addGps) {
finalInvoice = new GPSDecorator(finalInvoice, days);
}
// 5. Strategy Pattern: Process Payment
boolean paymentSuccess = payment.processPayment(finalInvoice.getTotal());
// 6. State Machine Transition
if (paymentSuccess) {
res.setStatus(ReservationStatus.CONFIRMED);
System.out.println("SUCCESS: Booking Confirmed for " + user.getUserId() + "! Total: $" + finalInvoice.getTotal());
} else {
res.setStatus(ReservationStatus.CANCELED);
System.out.println("FAIL: Payment declined. Reservation canceled.");
}
} catch (Exception e) {
System.out.println("ERROR for " + user.getUserId() + ": " + e.getMessage());
}
}
}
public class CarRentalSystem {
public static void main(String[] args) {
System.out.println("=== STARTING CAR RENTAL MULTITHREADED SIMULATION ===\n");
CarRentalSystem system = CarRentalSystem.getInstance();
Branch branch = new Branch();
// Setup fleet
branch.addVehicle(new Vehicle("NY-123", VehicleType.SUV, 100.0));
// Setup users
User alice = new User("U-01", "Alice", "DL-111");
User bob = new User("U-02", "Bob", "DL-222");
LocalDate start = LocalDate.of(2026, 8, 1);
LocalDate end = LocalDate.of(2026, 8, 10);
// Simulation 1: Alice successfully books the car with GPS
System.out.println("--> Alice is attempting to book NY-123...");
system.checkout(branch, "NY-123", alice, start, end,
new WeeklyDiscountPricingStrategy(), new CreditCardPayment(), true);
// Simulation 2: Bob tries to book the exact same car for the exact same dates
System.out.println("\n--> Bob is attempting to book NY-123 for the same dates...");
// The ReentrantLock and date-checking logic ensures this fails safely!
system.checkout(branch, "NY-123", bob, start, end,
new WeeklyDiscountPricingStrategy(), new CreditCardPayment(), false);
}
}