Skip to the workspace
Pebellslearn by building
Design Patterns  ›  Lesson

The Factory Method Pattern

GoF Design Patterns 15 minFactory Method moves the decision of which concrete class to create into one dedicated method, so the rest of the code works only with the abstraction.

software design architecture / The Factory Method Pattern

Explore each scene at your own pace.

01 · The rule

The rule

The Factory Method Pattern

Shelfwise charges Indian customers through a UPI gateway and everyone else by card. The same three lines, if country == "IN": gateway = UpiGateway() else: gateway = CardGateway(), appear in checkout, refunds and subscriptions. Adding a wallet option for one country means finding and editing all three, and hoping nobody made a fourth copy. Factory Method gives that decision one home.

The rule

Put "which class do I create?" in one method that returns the abstraction.

Callers want a PaymentGateway. They should not have to know which concrete class to build, or the rule for choosing it. A factory method holds that knowledge:

def gateway_for(country) -> PaymentGateway:
    if country == "IN":
        return UpiGateway()
    return CardGateway()

gateway = gateway_for(order.country)
gateway.charge(order.payment_details, order.total())

Checkout, refunds and subscriptions each call gateway_for(...) and then use only the PaymentGateway interface. None of them names UpiGateway or CardGateway. Adding a WalletGateway means writing that class and adding one line inside gateway_for; no caller changes.

In the classic object-oriented form, the factory method is a method on a base class that subclasses override to decide what gets made:

class ReportExporter(ABC):
    def export(self, figures):
        writer = self.create_writer()   # the factory method
        writer.write(figures)

    @abstractmethod
    def create_writer(self): ...

class CsvExporter(ReportExporter):
    def create_writer(self):
        return CsvWriter()

export holds the shared steps; each subclass decides which writer to create. Both forms share the same idea: creation is separated from use, and callers depend only on the abstraction.

It pairs naturally with Dependency Inversion. DIP says checkout should receive an abstraction; a factory is often the place that decides which concrete one to hand over.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.