Factory method
medium 60 minA fixed workflow with one open step that creates an object.
Video lesson · Chapter 1 of 6
Make a prediction
Factory method
1:04Reel

More reels
One idea each, a minute or less.
Factory method vs abstract factory
0:32Reel
Theory
Read or listen first. About 2 min.
What it is
Factory Method is a creational pattern. A base class, the creator, contains a workflow that needs an object. It gets the object from a method of its own, and subclasses override that method. So the base class uses an object whose class it does not know.
The pattern has two halves that are easy to mix up: the method that creates, and the workflow that uses the result. Without the workflow there is no reason for a base class, and a function does the job.
Think of a chain of restaurants. Head office writes how a burger is made and served. Each place decides which filling it uses, paneer here, beef there. The guest orders a burger.
Why it exists
A constructor call names a class. Code full of them can not be extended without being edited, and can not be tested without the real thing.
Frameworks need it most. Their authors write the workflow years before anyone writes the product. The hook method is how the two meet.
In interviews the word factory appears in nearly every object design round. Candidates who can tell a simple factory, a factory method and an abstract factory apart, and can say when none is needed, stand out.
A short history
1994
The book "Design Patterns" by Gamma, Helm, Johnson and Vlissides describes Factory Method among the creational patterns, next to Abstract Factory, Builder, Prototype and Singleton.
Java 5 (2004)
IterableandThreadFactoryjoin the Java library: one method that creates an iterator, and one object that creates threads on demand, instead of calls to new Thread.Java 6
AbstractExecutorServicegetsnewTaskFor, a protected factory method with a default, so that subclasses can supply their own kind of task.18 April 2007
PEP 3119 is created. It brings abstract base classes to Python, which make a missing override an error at creation.
Words to know
- Factory method
- A method that creates an object and can be overridden.
- Creator
- The class that declares the factory method and usually uses its result.
- Product
- The interface of what is created.
- Simple factory
- One function or class that decides by a value. Not a pattern of the book.
- Static factory method
- A named way to get an object of a class, such as
oforfrom_text. - Abstract factory
- An object with several creating methods whose products fit together.
- Registry
- A map from a name to a function that creates.
- Hook
- A method of a base class that is meant to be overridden.
- Parallel hierarchies
- Two class trees that grow together, one creator for each product.
- Virtual constructor
- An older name for the idea, used in the C++ FAQ: a method that has the effect of a constructor chosen at run time.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Client requests operation. The client calls the workflow of the creator without knowing which concrete class will be made.
Understand it
Start here
One recipe, many moulds
A workshop sells candles. Melting, pouring, cooling and cutting the wick are the same everywhere. Only the mould differs from branch to branch. The Factory Method pattern is that workshop in code: the steps are written once, and the one step that creates something is left open for each branch.
Compare the first and the third picture: the decision moved from a list that one person edits to an open line that each branch fills.
Four roles
Product
The interface that all created objects share:
Candle,Vehicle,Document. The workflow and the client know only this.Concrete product
Pillar,BmwM5,InvoicePdf. They do not know who created them.Creator
Declares the factory method and usually holds the workflow that uses the product. The method is abstract or has a default.
Concrete creator
Overrides the factory method and returns one kind of product, with everything that is special about building it.
The pattern as classes
1/3The abstract half
The creator works with the product interface. Both are abstract, and the arrow between them names no concrete class.
usesextends (is a)implements
Why
What goes wrong without it
Calling constructors all over the program ties each caller to concrete classes. When a new kind appears, or a constructor gets another parameter, edits spread through the code. The first repair is one method with conditions. It helps, and it has its own disease.
class Pillar: burn_hours = 40class Floating: burn_hours = 4class Workshop: def make(self, branch): if branch == "hill": candle = Pillar() elif branch == "harbour": candle = Floating() else: candle = Pillar() # somebody had to decide something return f"{type(candle).__name__} cooled, wick cut, boxed" def price_tag(self, branch): if branch == "hill": # the same question again return "40 hours" return "4 hours" # and another defaultshop = Workshop()print(shop.make("forest"), "|", shop.price_tag("forest"))Two methods ask the same question and have different defaults. The kind of a candle is not written in one place, it is spread over conditions. The design below shows what depends on what.
The design that hurts
1/2Two kinds
The workshop knows both classes.
depends on
The idea
Call a method that does not exist yet
In the base class the recipe calls take_mould(). The base class has no body for it. Every subclass supplies one. The steps stay in one place and the choice moves into the subclass.
from abc import ABC, abstractmethodclass Candle(ABC): @abstractmethod def burn_hours(self): ...class Pillar(Candle): def burn_hours(self): return 40class Floating(Candle): def burn_hours(self): return 4class Workshop(ABC): def make(self): # the recipe card candle = self.take_mould() # the open line name = type(candle).__name__ return f"{name} cooled, wick cut, boxed | {candle.burn_hours()} hours" @abstractmethod def take_mould(self) -> Candle: ... # the factory methodclass HillBranch(Workshop): def take_mould(self): return Pillar()class HarbourBranch(Workshop): def take_mould(self): return Floating()class Star(Candle): # later, a new branch def burn_hours(self): return 6class ForestBranch(Workshop): def take_mould(self): return Star()for branch in (HillBranch(), HarbourBranch(), ForestBranch()): print(branch.make())try: Workshop()except TypeError as error: print("the card alone makes nothing:", type(error).__name__)One call, seen from inside
How to build it
| Step | Do | Example |
|---|---|---|
| 1 | Write the product interface from what the workflow needs | Candle.burn_hours() |
| 2 | Write the concrete products | Pillar, Floating |
| 3 | Write the creator: the workflow, and an abstract factory method | Workshop.make, take_mould |
| 4 | Write one concrete creator per variant | HillBranch |
| 5 | Let the client work with the creator type | branch.make() |
| 6 | Choose the creator in one place | main, a configuration, a registry |
Principles
What it gives you
Open for new kinds
A new kind is new classes. The existing creators are not edited. See open closed.
Dependencies turned around
The workflow depends on
Candle, not onPillar. See dependency inversion.One home for building
The details of building one kind sit in one creator.
A seam for tests
A test creator can return a small fake product.
What a new kind costs
Who creates? A decision
A report job must write to PDF today and to Markdown next month. The steps before and after are the same. How do you create the document?
Breaksif in the job, with a default
- How
if kind == 'pdf': ... else: ...- Limit
- The else produces Markdown for every typing mistake, and the same if appears in the test, the mail and the preview.
- Choose when
- Never with a silent else.
WorksA publisher with a factory method
- How
PdfPublisherandMarkdownPublisheroverridecreate_document.- Limit
- Two classes per format. Heavy, if only this object differs.
- Choose when
- When formats also differ in other steps, such as page numbers or signing.
StrongOne publisher that receives a function
- How
Publisher(make_document=PdfDocument), chosen in main from a map of known formats.- Limit
- No place for a second difference. Then grow into the pattern.
- Choose when
- When the created object is the only difference.
Use it when
- A workflow is fixed and one object in it varies
- The exact class is not known to the base class
- Users of your framework must plug in their own classes
- Knowledge about building one kind should have one home
- Return the interface, and let one creator take a parameter for close relatives
Leave it when
- There is one product
- The constructor call is trivial and will stay so
- Kinds differ in numbers, not in behaviour
- A function or a simple factory is enough
- Callers would cast the product back to its class
Relatives
Simple factory, factory method, abstract factory
| Simple factory | Factory method | Abstract factory | |
|---|---|---|---|
| Form | One function or class with a decision | An overridable method | An object with several creating methods |
| Chosen by | A value | Which subclass you have | Which factory object you were given |
| Makes | One product | One product inside a workflow | Products that fit together |
| Mechanism | Condition or map | Inheritance | Composition |
| New kind | Edit one place | New subclass | New factory class |
| Book pattern? | No | Yes | Yes |
| Pattern | Question it answers |
|---|---|
| Factory method | Which class, decided by a subclass |
| Builder | How to put a complex object together, step by step |
| Prototype | Which example to copy |
| Template method | Which steps vary. A factory method is often one of its hooks |
| Strategy | Which behaviour to use, passed in from outside |
| Singleton | How to have only one |
Summary
The whole topic in one minute.
Write the steps once, in a creator. Where the steps need an object, call a method that subclasses override. Clients see the creator and the product interface, so a new kind is a new product, a new creator and one line of choice.
Then ask whether you need the tree at all. If a value chooses, use a simple factory or a sealed registry. If only the object differs, pass a function. Keep the promises of creation in writing: ready, new or shared, cleaned up on failure, and never called from a constructor.
- A fixed workflow calls an abstract creating method. Subclasses decide what it returns.
- Product, concrete product, creator, concrete creator. The client knows the first and the third.
- A simple factory decides by a value in one place. A factory method decides by which subclass you have.
- A new kind is new classes and one line of choice. Nobody removes the choice.
- If only the object varies, pass a function. Inheritance is for several differences.
- The override must keep the contract: ready, never empty, new or shared as promised.
Sources
- Wikipedia: Factory method pattern
- Design Patterns, publisher page (InformIT)
- Python logging: Logger.makeRecord
- Java AbstractExecutorService
- Java ThreadFactory
- DbConnection.CreateDbCommand (.NET)
- QStyledItemDelegate (Qt)
- Django editing mixins
- Spring AbstractFactoryBean
- C++ FAQ: virtual functions in constructors
- Python entry points
- Java ServiceLoader
- PEP 3119, abstract base classes