What Is the 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 using direct instantiation (new or ClassName()), the pattern delegates object creation to a specialized method—often called a factory method.
It’s useful when the exact type of the object isn't known until runtime or when object creation involves logic that you'd rather not repeat throughout your code.
Real-World Analogy
Imagine a car factory. You don’t build cars yourself—you place an order, and the factory produces the right model based on your request. You say “I want a Sedan,” and boom—a Sedan rolls out. You didn’t worry about assembling engines or installing doors. That’s the factory’s job.
Python Code Example
Define a Common Interface
class Vehicle:
def drive(self):
raise NotImplementedError("Subclass must implement drive method")
Concrete Implementations
class Car(Vehicle):
def drive(self):
print("Driving a car")
class Bike(Vehicle):
def drive(self):
print("Riding a bike")
Factory Class
class VehicleFactory:
@staticmethod
def create_vehicle(vehicle_type):
if vehicle_type == "car":
return Car()
elif vehicle_type == "bike":
return Bike()
else:
raise ValueError("Unknown vehicle type")
Using The Factory
vehicle1 = VehicleFactory.create_vehicle("car")
vehicle1.drive() # Output: Driving a car
vehicle2 = VehicleFactory.create_vehicle("bike")
vehicle2.drive() # Output: Riding a bike