The before code mixes all parking logic inside one method using conditionals, making it hard to extend. The after code defines a ParkingStrategy interface and separate classes for each strategy. ParkingSystem uses a strategy instance to delegate parking decisions, enabling easy swapping and extension.
### Before: Without Strategy Pattern
class ParkingSystem:
def park_car(self, car, strategy):
if strategy == 'first_available':
# find first available spot
pass
elif strategy == 'nearest_entrance':
# find spot nearest to entrance
pass
else:
# default parking
pass
### After: With Strategy Pattern
from abc import ABC, abstractmethod
class ParkingStrategy(ABC):
@abstractmethod
def find_spot(self, parking_lot, car):
pass
class FirstAvailableStrategy(ParkingStrategy):
def find_spot(self, parking_lot, car):
# logic to find first available spot
return 'Spot1'
class NearestEntranceStrategy(ParkingStrategy):
def find_spot(self, parking_lot, car):
# logic to find spot nearest entrance
return 'Spot2'
class ParkingSystem:
def __init__(self, strategy: ParkingStrategy):
self.strategy = strategy
def park_car(self, car):
spot = self.strategy.find_spot(None, car)
print(f'Parking car at {spot}')
# Usage
system = ParkingSystem(FirstAvailableStrategy())
system.park_car('CarA')
system.strategy = NearestEntranceStrategy()
system.park_car('CarB')