Factory Method in Parking Lot 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.
+ getSize(): int
+ getSize()
+ getSize()
+ getSize()
+ findSpot(vehicle): ParkingSpot
+ findSpot()
+ findSpot()
+ findSpot()
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.
strategy = getStrategyForVehicleType(type)
vehicle = strategy.createVehicle(id, plate)
spot = strategy.findSpot(vehicle)
spot.park(vehicle)
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.