CreationalPythonverifiedVerified

Factory Method Pattern in Python

Defines an interface for creating an object but lets subclasses decide which class to instantiate. Defers instantiation to subclasses.

How to Implement the Factory Method Pattern in Python

1Step 1: Define the product interface using Protocol

from abc import ABC, abstractmethod


class Transport(ABC):
    @abstractmethod
    def deliver(self, cargo: str) -> str: ...

2Step 2: Implement concrete products

class Truck(Transport):
    def deliver(self, cargo: str) -> str:
        return f'Delivering "{cargo}" by road in a truck'


class Ship(Transport):
    def deliver(self, cargo: str) -> str:
        return f'Delivering "{cargo}" by sea in a ship'

3Step 3: Create the abstract creator with the factory method

class Logistics(ABC):
    @abstractmethod
    def create_transport(self) -> Transport: ...

    def plan_delivery(self, cargo: str) -> str:
        transport = self.create_transport()
        return transport.deliver(cargo)

4Step 4: Wire up concrete creators and test

class RoadLogistics(Logistics):
    def create_transport(self) -> Transport:
        return Truck()


class SeaLogistics(Logistics):
    def create_transport(self) -> Transport:
        return Ship()


logistics: Logistics = RoadLogistics()
print(logistics.plan_delivery("Electronics"))

sea_logistics: Logistics = SeaLogistics()
print(sea_logistics.plan_delivery("Grain"))

Factory Method Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Factory Method Pattern in the Real World

Think of a logistics company that ships packages. The headquarters defines the shipping process but doesn’t decide the vehicle. Regional offices (subclasses) choose whether to use trucks, ships, or drones based on local conditions. The headquarters just says ‘get me a transport’ and the regional office delivers the right one.