The before code creates a Car object directly, which ties client code to a specific class. The after code uses a factory method to create car objects, allowing easy extension to new car types without changing client code.
### Before: Direct instantiation (tight coupling)
class Car:
def __init__(self, model):
self.model = model
car = Car('Sedan')
### After: Using Factory Method pattern
from abc import ABC, abstractmethod
class Car(ABC):
@abstractmethod
def drive(self):
pass
class Sedan(Car):
def drive(self):
print('Driving a sedan')
class Suv(Car):
def drive(self):
print('Driving an SUV')
class CarFactory:
@staticmethod
def create_car(car_type):
if car_type == 'sedan':
return Sedan()
elif car_type == 'suv':
return Suv()
else:
raise ValueError('Unknown car type')
car = CarFactory.create_car('sedan')
car.drive()