Solution
Factory Pattern: The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. Instead of calling a constructor directly, you call a factory method that returns an instance of a class. This centralizes object creation logic and decouples the client code from concrete classes.
How it differs from directly creating objects:
| Aspect | Direct Object Creation | Factory Pattern |
|---|---|---|
| Approach | Client uses the new keyword to instantiate a specific class directly. | Client calls a factory method that creates and returns the appropriate object. |
| Flexibility | Tight coupling—changes to a class require updating all client code that creates it. | Loose coupling—the factory can change the object creation logic without affecting client code. |
| Complexity | Simple for straightforward scenarios; hard to manage when object creation involves complex logic. | Complex to set up initially, but simplifies client code and centralizes logic. |
| Maintainability | Harder to maintain—every client must be updated if the creation process changes. | Easier to maintain—changes are made in the factory class only. |
Example:
Without Factory Pattern (Direct Creation):
# Direct object creation
car = Car("Sedan", "Red")
bike = Bike("Mountain", "Blue")
With Factory Pattern:
class VehicleFactory:
def create_vehicle(self, vehicle_type, model, color):
if vehicle_type == "car":
return Car(model, color)
elif vehicle_type == "bike":
return Bike(model, color)
else:
raise ValueError("Unknown vehicle type")
# Client code
factory = VehicleFactory()
car = factory.create_vehicle("car", "Sedan", "Red")
bike = factory.create_vehicle("bike", "Mountain", "Blue")
The Factory Pattern abstracts the instantiation logic, making it easier to add new vehicle types without changing client code and centralizing any changes to the creation process.