Skip to content

factory pattern

The factory pattern is a way of creating objects through a dedicated function or method, called a factory, instead of calling a class constructor directly. The caller asks for the kind of object it needs, and the factory decides which concrete class to build and how to set it up.

It’s one of the creational patterns in the design pattern catalog, the group of patterns that deal with how objects get created. The payoff is that code which uses an object no longer needs to know which class produced it, so adding a new class touches the factory rather than every call site.

Say a reporting app lets each user download results as JSON or CSV. Rather than scattering if checks through the code, one factory maps the requested format to an exporter class and returns a ready-to-use instance:

Language: Python
>>> import json

>>> class JSONExporter:
...     def export(self, rows):
...         return json.dumps(rows)
...
>>> class CSVExporter:
...     def export(self, rows):
...         lines = [",".join(rows[0].keys())]
...         lines += [",".join(map(str, row.values())) for row in rows]
...         return "\n".join(lines)
...
>>> def make_exporter(file_format):
...     exporters = {"json": JSONExporter, "csv": CSVExporter}
...     return exporters[file_format]()
...
>>> rows = [{"name": "Ada", "score": 98}]
>>> make_exporter("json").export(rows)
'[{"name": "Ada", "score": 98}]'
>>> print(make_exporter("csv").export(rows))
name,score
Ada,98

Supporting a new format means writing one more class and adding one line to the factory’s mapping. The calling code only knows that it gets back something with an .export() method, as this flow shows:

Calling code asks make_exporter() for a format, which builds JSONExporter or CSVExporter and returns an object with .export().
One Factory Picks the Class, the Caller Gets an Object

How It Shows Up in Practice

A Python developer meets factories constantly, often without the label. The standard library’s collections.namedtuple() is documented as a factory function that builds a new tuple subclass. Alternate constructors such as dict.fromkeys() and datetime.fromtimestamp() are class methods that build and return an instance of their own class, which makes them factories too.

In application code, factories tend to appear wherever the right object depends on configuration, user input, or the environment. A factory is a natural place to read a feature flag or a settings value, so switching a payment provider or storage backend changes one function instead of many modules.

Factories also pair well with dependency injection. The factory builds the concrete object, and the rest of the code receives it, which lets a test swap in a fake without patching constructors. When the set of classes grows or comes from plugins, the mapping inside the factory often becomes a registry.

Common Variations

The name covers a few related shapes, and teams use it loosely for all of them:

  • Simple factory: A plain function, like make_exporter() above, that picks and builds a class from its arguments.
  • Factory method: A method that subclasses override to decide which class to instantiate. The Gang of Four book, Design Patterns: Elements of Reusable Object-Oriented Software, defines this as the pattern that lets a class defer instantiation to subclasses.
  • Abstract factory: An object that creates a whole family of related objects, such as matching widgets for one user interface theme.

Because Python classes and functions are first-class objects, a simple factory is often all a project needs. Wrapping a single class in a factory before a second one exists adds indirection with no benefit, which runs against the YAGNI principle.

The Factory Method Pattern and Its Implementation in Python

Tutorial

The Factory Method Pattern and Its Implementation in Python

In this Python tutorial, you'll learn about the Factory Method design pattern and its implementation. You'll understand the components of Factory Method, when to use it, and how to modify existing code to leverage it. You'll also see a general purpose implementation of Factory Method in Python.

intermediate best-practices

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Martin Breuss • Updated Oct. 26, 2026