Creational PatternsFactory Method PatternMedium⏱️ ~2 min

Factory Method in Parking Lot System

Domain Application: Vehicle Parking System

Consider a parking lot system that handles different vehicle types: motorcycles, cars, and trucks. Each vehicle type requires different parking spot allocation logic. The Factory Method Pattern allows us to create vehicle-specific parking strategies without coupling the main parking logic to concrete vehicle classes.

«interface»
Vehicle
+ getType(): VehicleType
+ getSize(): int
Motorcycle
+ getType()
+ getSize()
Car
+ getType()
+ getSize()
Truck
+ getType()
+ getSize()
ParkingStrategy
+ createVehicle(id, plate): Vehicle
+ findSpot(vehicle): ParkingSpot
MotorcycleStrategy
+ createVehicle()
+ findSpot()
CarStrategy
+ createVehicle()
+ findSpot()
TruckStrategy
+ createVehicle()
+ findSpot()
Design Decisions:

First, ParkingStrategy acts as the Creator with createVehicle() as the factory method. Second, each concrete strategy (MotorcycleStrategy, CarStrategy, TruckStrategy) creates its specific vehicle type. Third, the findSpot() method uses the vehicle returned by createVehicle() without knowing its concrete type. Fourth, the client code works with ParkingStrategy interface and does not depend on concrete vehicle classes.

Usage Flow:

strategy = getStrategyForVehicleType(type)
vehicle = strategy.createVehicle(id, plate)
spot = strategy.findSpot(vehicle)
spot.park(vehicle)

Interview Tip: In interviews, mention that you could extend this to handle electric vehicles by adding an ElectricCarStrategy without modifying existing code. This demonstrates the Open/Closed Principle (OCP).
Alternative Consideration:

If parking logic does not vary by vehicle type and only the vehicle creation differs, a Simple Factory might suffice. However, if each vehicle type requires unique spot-finding algorithms (motorcycles can share spots, trucks need multiple spots), Factory Method provides better separation of concerns.

💡 Key Takeaways
ParkingStrategy is the Creator with createVehicle() as factory method
Each concrete strategy creates a specific vehicle type and implements custom parking logic
Client code depends on ParkingStrategy and Vehicle interfaces, not concrete classes
Easy to add new vehicle types (Electric, Bus) without modifying existing strategies
📌 Examples
1MotorcycleStrategy creates Motorcycle and finds compact spots
2TruckStrategy creates Truck and allocates multiple adjacent spots
3CarStrategy creates Car and finds standard spots
← Back to Factory Method Pattern Overview
Factory Method in Parking Lot System | Factory Method Pattern - System Overflow