Strategy Pattern - Parking Lot Payment System
Domain: Parking Lot Fee Calculation
A parking lot needs different fee calculation strategies based on vehicle type. Motorcycles, cars, and trucks have different pricing models. Additionally, special pricing (weekend rates, early bird discounts) must be applied dynamically.
Design Without Strategy Pattern
A violation would look like this:
- vehicleType: String
- entryTime: DateTime
+ calculateFee(): Money
if vehicleType == "MOTORCYCLE":
return duration * 10
else if vehicleType == "CAR":
if isWeekend():
return duration * 25
return duration * 20
else if vehicleType == "TRUCK":
return duration * 50
This design forces all pricing logic into ParkingTicket, making it impossible to add new vehicle types or pricing models without modification.
Strategy Pattern Solution
- exitTime: DateTime
- pricingStrategy: PricingStrategy
+ calculateFee(): Money
Implementation Details
Strategy Interface: The PricingStrategy interface declares calculateFee(duration, entryTime). Passing entryTime allows time-based strategies (like early bird discounts) to make decisions. Duration is already calculated by ParkingTicket from entry and exit times.
Concrete Strategies: Each pricing class implements its own logic. For example, MotorcyclePricing applies a flat rate of 10 per hour. CarPricing uses 20 per hour. WeekendPricing checks if entryTime falls on Saturday or Sunday and adjusts rates accordingly. TruckPricing might have tiered pricing (first 2 hours at 50, then 40 per additional hour).
Context Usage: When a vehicle enters, the system creates a ParkingTicket and assigns the appropriate strategy based on vehicle type. If special pricing applies (weekend, event day), a decorator pattern could wrap the base strategy, but for simplicity, a separate strategy class is used. When the vehicle exits, calculateFee() delegates to the current strategy.
Benefits in This Domain
First, adding electric vehicle pricing requires only a new ElectricVehiclePricing class without touching existing code. Second, seasonal promotions become new strategies deployed independently. Third, each strategy can be unit tested with mock durations. Fourth, business analysts can specify pricing rules that map directly to strategy classes.