Article · Factory Method · Abstract Factory
Factory Method – let the subclass decide what gets created
Factory Method separates the algorithm that uses an object from the decision about which exact object is created. A ticket booking example in C#, TypeScript, Java, Go and Python.
Code that creates something and code that uses it often live in the same method – until the day the product needs a second variant. Factory Method moves the decision "which class do I instantiate" into a separate, overridable method, so the rest of the algorithm never learns about concrete types.
- 1994
- year "Design Patterns" was published – Gamma, Helm, Johnson, Vlissides
- 5
- creational patterns in the GoF catalog – this is the first one on our path
- 2
- class hierarchies – creators and products grow side by side
The problem: a booking that knows too much
You are building a ticket sales service. At first there are only concerts: a customer books a seat, the system issues a ticket with a seat number and emails it. Then festivals arrive (a multi-day wristband with no numbered seats), and soon webinars (a streaming link). The easiest path looks like this:
class BookingService {
book(kind: "concert" | "festival" | "webinar", holder: string): Ticket {
let ticket: Ticket;
if (kind === "concert") ticket = new SeatTicket(holder, this.pickSeat());
else if (kind === "festival") ticket = new WristbandPass(holder, 3);
else ticket = new StreamAccess(holder, this.generateLink());
this.mailer.send(holder, ticket.describe()); // the part that never changes
return ticket;
}
}It works, but every new kind of event means editing the same method, adding another if branch and retesting the delivery logic nobody actually touched. The class breaks the open–closed principle from SOLID: it is open for modification instead of extension.
The solution: extract the decision into a method
The base class keeps what is shared – validation, delivery, logging – and the bare new goes behind an abstract createTicket() method. Every kind of event becomes a subclass that overrides just that one method. The book() algorithm talks only to the Ticket interface.
| Role | In the example | Responsibility |
|---|---|---|
| Product | Ticket | the common interface of everything that can be created |
| Concrete product | SeatTicket, WristbandPass | concrete ticket variants |
| Creator | BookingFlow | the algorithm that uses the product + the factory method declaration |
| Concrete creator | ConcertBooking, FestivalBooking | decides which product to create |
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Notice that the creator is not a "factory" in the everyday sense – its main job is booking, and creating the ticket is just one step. That is what separates Factory Method from a class that does nothing but build objects.
Implementation in five languages
In C#, TypeScript, Java and Python we use classic inheritance. Go has no subclasses, so an injected TicketMaker function plays the role of the factory method – the same idea expressed through composition instead of a hierarchy.
BookingFlow.createTicket()
var flows = new BookingFlow[] { new ConcertBooking(), new FestivalBooking() };
foreach (var flow in flows)
flow.Book("Ola");
public interface ITicket
{
string Describe();
}
public sealed record SeatTicket(string Holder, string Seat) : ITicket
{
public string Describe() => $"Seat {Seat} for {Holder}";
}
public sealed record WristbandPass(string Holder, int Days) : ITicket
{
public string Describe() => $"{Days}-day wristband for {Holder}";
}
// Creator: the booking algorithm is fixed, the kind of ticket is not.
public abstract class BookingFlow
{
public ITicket Book(string holder)
{
ArgumentException.ThrowIfNullOrWhiteSpace(holder);
var ticket = CreateTicket(holder); // the factory method
Console.WriteLine($"Sending: {ticket.Describe()}");
return ticket;
}
protected abstract ITicket CreateTicket(string holder);
}
public sealed class ConcertBooking : BookingFlow
{
protected override ITicket CreateTicket(string holder) => new SeatTicket(holder, "B-12");
}
public sealed class FestivalBooking : BookingFlow
{
protected override ITicket CreateTicket(string holder) => new WristbandPass(holder, 3);
}interface Ticket {
describe(): string;
}
class SeatTicket implements Ticket {
constructor(private readonly holder: string, private readonly seat: string) {}
describe(): string {
return `Seat ${this.seat} for ${this.holder}`;
}
}
class WristbandPass implements Ticket {
constructor(private readonly holder: string, private readonly days: number) {}
describe(): string {
return `${this.days}-day wristband for ${this.holder}`;
}
}
// Creator: the booking algorithm is fixed, the kind of ticket is not.
abstract class BookingFlow {
book(holder: string): Ticket {
if (!holder.trim()) throw new Error("Holder is required");
const ticket = this.createTicket(holder); // the factory method
console.log(`Sending: ${ticket.describe()}`);
return ticket;
}
protected abstract createTicket(holder: string): Ticket;
}
class ConcertBooking extends BookingFlow {
protected createTicket(holder: string): Ticket {
return new SeatTicket(holder, "B-12");
}
}
class FestivalBooking extends BookingFlow {
protected createTicket(holder: string): Ticket {
return new WristbandPass(holder, 3);
}
}
for (const flow of [new ConcertBooking(), new FestivalBooking()]) flow.book("Ola");import java.util.List;
interface Ticket {
String describe();
}
record SeatTicket(String holder, String seat) implements Ticket {
public String describe() { return "Seat " + seat + " for " + holder; }
}
record WristbandPass(String holder, int days) implements Ticket {
public String describe() { return days + "-day wristband for " + holder; }
}
// Creator: the booking algorithm is fixed, the kind of ticket is not.
abstract class BookingFlow {
public final Ticket book(String holder) {
if (holder == null || holder.isBlank()) throw new IllegalArgumentException("Holder is required");
Ticket ticket = createTicket(holder); // the factory method
System.out.println("Sending: " + ticket.describe());
return ticket;
}
protected abstract Ticket createTicket(String holder);
}
class ConcertBooking extends BookingFlow {
@Override
protected Ticket createTicket(String holder) { return new SeatTicket(holder, "B-12"); }
}
class FestivalBooking extends BookingFlow {
@Override
protected Ticket createTicket(String holder) { return new WristbandPass(holder, 3); }
}
public class Tickets {
public static void main(String[] args) {
List<BookingFlow> flows = List.of(new ConcertBooking(), new FestivalBooking());
flows.forEach(flow -> flow.book("Ola"));
}
}package main
import (
"errors"
"fmt"
)
type Ticket interface {
Describe() string
}
type SeatTicket struct{ Holder, Seat string }
func (t SeatTicket) Describe() string { return fmt.Sprintf("Seat %s for %s", t.Seat, t.Holder) }
type WristbandPass struct {
Holder string
Days int
}
func (p WristbandPass) Describe() string {
return fmt.Sprintf("%d-day wristband for %s", p.Days, p.Holder)
}
// Go has no inheritance: the factory method is a function value injected into the flow.
type TicketMaker func(holder string) Ticket
type BookingFlow struct{ makeTicket TicketMaker }
func (f BookingFlow) Book(holder string) (Ticket, error) {
if holder == "" {
return nil, errors.New("holder is required")
}
t := f.makeTicket(holder)
fmt.Println("Sending:", t.Describe())
return t, nil
}
func main() {
concert := BookingFlow{makeTicket: func(h string) Ticket { return SeatTicket{Holder: h, Seat: "B-12"} }}
festival := BookingFlow{makeTicket: func(h string) Ticket { return WristbandPass{Holder: h, Days: 3} }}
for _, flow := range []BookingFlow{concert, festival} {
if _, err := flow.Book("Ola"); err != nil {
fmt.Println(err)
}
}
}from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Protocol
class Ticket(Protocol):
def describe(self) -> str: ...
@dataclass(frozen=True)
class SeatTicket:
holder: str
seat: str
def describe(self) -> str:
return f"Seat {self.seat} for {self.holder}"
@dataclass(frozen=True)
class WristbandPass:
holder: str
days: int
def describe(self) -> str:
return f"{self.days}-day wristband for {self.holder}"
class BookingFlow(ABC):
"""Creator: the booking algorithm is fixed, the kind of ticket is not."""
def book(self, holder: str) -> Ticket:
if not holder.strip():
raise ValueError("holder is required")
ticket = self.create_ticket(holder) # the factory method
print(f"Sending: {ticket.describe()}")
return ticket
@abstractmethod
def create_ticket(self, holder: str) -> Ticket: ...
class ConcertBooking(BookingFlow):
def create_ticket(self, holder: str) -> Ticket:
return SeatTicket(holder, seat="B-12")
class FestivalBooking(BookingFlow):
def create_ticket(self, holder: str) -> Ticket:
return WristbandPass(holder, days=3)
if __name__ == "__main__":
for flow in (ConcertBooking(), FestivalBooking()):
flow.book("Ola")Step by step
- Step 1 Find new inside the algorithm – Look for places where choosing a class is mixed with logic you want to keep unchanged.
- Step 2 Extract the product interface – All variants must satisfy a common contract that the algorithm relies on (describe()).
- Step 3 Add the factory method – Declare createTicket() in the base class – abstract or with a sensible default implementation.
- Step 4 Move the variants into subclasses – Each if branch becomes a subclass that overrides only the factory method.
- Step 5 Delete the conditionals – Choosing the subclass moves to the edge of the system – configuration, a DI container or a single composition root.
When to use it and when not to
Pros
- a new product variant is a new class, not an edit of working code
- the algorithm depends on an abstraction, so it is easy to test with a fake product
- one place for complex creation logic (defaults, validation)
- a natural extension point for frameworks and libraries
Cons
- every variant needs its own creator subclass
- the creator and product hierarchies grow in parallel
- with two variants and no prospect of a third, it is just overhead
The pattern pays off when you have a stable algorithm and a growing list of product variants, or when you write a library whose users should plug in their own objects. Skip it if there is a single variant and "maybe one day there will be a second" – YAGNI wins.
Factory Method and testing
For a tester this is one of the friendliest patterns. Since the book() algorithm receives a ticket only through createTicket(), a test needs nothing more than a tiny subclass – or, in the functional variant, a lambda – that returns a fake ticket with a predictable description. You then check the booking logic alone: validation, delivery, error handling, without picking random seats or generating streaming links. It works the other way round, too: each concrete creator has so little code that its test boils down to a single assertion, "ConcertBooking issues a SeatTicket". If you are writing tests for code with a giant switch on types, extracting a factory method is often the cheapest first refactoring step.
Related patterns
Factory Method is often a step inside a Template Method – just like book() is the template here and createTicket() its replaceable step. When you need to create a family of matching objects, several factory methods gather into one object – that is Abstract Factory. If you would rather copy a ready-made instance than build one from scratch, look at Prototype.
Abstract Factory – Whole families of products instead of one
Template Method – An algorithm skeleton with replaceable steps
Prototype – Creating by copying a ready-made instance
In practice: where you already use it
- .NET –
ILoggerProvider.CreateLogger(categoryName): each provider (console, debug, third-party libraries) returns its ownILoggerimplementation, whileLoggerFactoryworks only with the interface. - Java –
Iterable.iterator(): every collection creates its own iterator, and the for-each loop knows onlyIterator. In Spring,FactoryBean<T>.getObject()plays a similar role. - Go – the
database/sql/driver.Driverinterface withOpen(name string) (Conn, error): thedatabase/sqlpackage uses connections, and each driver decides which exact connection it creates. - Python – in Django class-based views,
get_form_class()andget_queryset()are factory methods you override in a subclass;__iter__is a method that creates an iterator as well. - Node/TypeScript – in NestJS a provider with
useFactorymoves the creation decision into a function; this is the "factory method as a parameter" variant.
Quick check
Question: Which piece of code is a Factory Method in the GoF sense?
- A static Ticket.create(kind) method with a switch on the ticket kind
- The abstract createTicket() in BookingFlow, overridden by ConcertBooking
- The SeatTicket(holder, seat) constructor with parameter validation
Interview question: how does Factory Method differ from Abstract Factory?
Factory Method is a single method in a class whose main job is something else (booking, in our case); you pick the variant through inheritance or by injecting a function. Abstract Factory is a separate object with several methods that create products of one family (e.g. a charge, a refund and a webhook verifier of the same provider); you pick the variant by passing a different factory object. Abstract factories are frequently implemented with factory methods.
Summary
Factory Method is a way to stop an algorithm from guessing which object to create. You extract that decision into one overridable method and gain a place where the system grows by adding classes rather than by appending if branches. The next step on the path – Abstract Factory – shows what to do when objects have to match each other in whole families.