Simple definition#
The Factory Method pattern declares a method for creating an object in a base class, and lets subclasses decide which concrete class to instantiate. The base class contains the code that uses the object; subclasses supply only the creation step.
GoF intent: “Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.” The book also calls it a virtual constructor.
The problem#
A reporting module exports sales data. The export workflow is always the same: validate the rows, create a writer, build a file name with the right extension, write the content. Only the writer differs — CSV for finance, JSON for an API consumer.
A first version hard-codes the choice:
ExportedFile export(String baseName, List<SalesRow> rows, String format) {
if (rows.isEmpty()) throw new IllegalArgumentException("Nothing to export");
ReportWriter writer = format.equals("csv") ? new CsvReportWriter() : new JsonReportWriter();
...
}
The workflow and the choice of class are tangled together. Adding a format means editing the workflow, and a framework that ships export cannot know which formats its users will add.
Real-world analogy#
A franchise restaurant chain publishes a fixed process for serving a meal: take the order, prepare the dish, plate it, serve it. Each franchise decides what “prepare the dish” produces according to local menus. Head office owns the process; the franchise owns one step.
Structure#
Four roles:
- Product — the interface of the objects created (
ReportWriter). - ConcreteProduct — implementations (
CsvReportWriter,JsonReportWriter). - Creator — declares the factory method and usually contains the workflow that uses the product (
ReportExporter). - ConcreteCreator — overrides the factory method to return a specific product (
CsvReportExporter,JsonReportExporter).
classDiagram
direction TB
class ReportExporter {
<<abstract>>
#createWriter()* ReportWriter
+export(String, List~SalesRow~) ExportedFile
}
class CsvReportExporter {
#createWriter() ReportWriter
}
class JsonReportExporter {
#createWriter() ReportWriter
}
class ReportWriter {
<<interface>>
+fileExtension() String
+write(List~SalesRow~) String
}
class CsvReportWriter
class JsonReportWriter
ReportExporter <|-- CsvReportExporter
ReportExporter <|-- JsonReportExporter
ReportWriter <|.. CsvReportWriter
ReportWriter <|.. JsonReportWriter
ReportExporter ..> ReportWriter : uses
CsvReportExporter ..> CsvReportWriter : creates
JsonReportExporter ..> JsonReportWriter : createssequenceDiagram
participant Client as FactoryMethodDemo
participant E as CsvReportExporter
participant W as CsvReportWriter
Client->>E: export("q3-sales", rows)
Note over E: inherited workflow in ReportExporter
E->>E: createWriter()
E->>W: new CsvReportWriter()
E->>W: fileExtension()
W-->>E: "csv"
E->>W: write(rows)
W-->>E: "region,units\n..."
E-->>Client: ExportedFile("q3-sales.csv", ...)Java implementation#
The full example is in examples/java/src/hub/patterns/factorymethod/. CI compiles and runs it with Java 21.
Product and concrete products#
package hub.patterns.factorymethod;
import java.util.List;
/** Product: the object the factory method creates. */
public interface ReportWriter {
String fileExtension();
String write(List<SalesRow> rows);
}package hub.patterns.factorymethod;
import java.util.List;
import java.util.stream.Collectors;
/** Concrete product. */
public final class CsvReportWriter implements ReportWriter {
@Override
public String fileExtension() {
return "csv";
}
@Override
public String write(List<SalesRow> rows) {
return rows.stream()
.map(r -> r.region() + "," + r.units())
.collect(Collectors.joining("\n", "region,units\n", ""));
}
}package hub.patterns.factorymethod;
import java.util.List;
import java.util.stream.Collectors;
/** Concrete product. Hand-written JSON keeps the example dependency-free. */
public final class JsonReportWriter implements ReportWriter {
@Override
public String fileExtension() {
return "json";
}
@Override
public String write(List<SalesRow> rows) {
return rows.stream()
.map(r -> "{\"region\":\"" + r.region() + "\",\"units\":" + r.units() + "}")
.collect(Collectors.joining(",", "[", "]"));
}
}Creator and concrete creators#
package hub.patterns.factorymethod;
import java.util.List;
/**
* Creator. export() contains the stable workflow; the one step that varies —
* which ReportWriter to use — is deferred to subclasses via the factory method.
*/
public abstract class ReportExporter {
/** The factory method. Subclasses decide which concrete product to create. */
protected abstract ReportWriter createWriter();
public final ExportedFile export(String baseName, List<SalesRow> rows) {
if (rows.isEmpty()) {
throw new IllegalArgumentException("Nothing to export");
}
ReportWriter writer = createWriter();
String fileName = baseName + "." + writer.fileExtension();
return new ExportedFile(fileName, writer.write(rows));
}
public record ExportedFile(String name, String content) {
}
}package hub.patterns.factorymethod;
/** Concrete creator: overrides the factory method to produce CSV writers. */
public final class CsvReportExporter extends ReportExporter {
@Override
protected ReportWriter createWriter() {
return new CsvReportWriter();
}
}package hub.patterns.factorymethod;
/** Concrete creator: overrides the factory method to produce JSON writers. */
public final class JsonReportExporter extends ReportExporter {
@Override
protected ReportWriter createWriter() {
return new JsonReportWriter();
}
}For contrast: a simple factory#
package hub.patterns.factorymethod;
import java.util.Locale;
/**
* NOT the GoF Factory Method: this is a "simple factory" — one static method
* that selects a class with a conditional. Useful, common, and different.
*/
public final class ReportWriters {
private ReportWriters() {
}
public static ReportWriter forFormat(String format) {
return switch (format.toLowerCase(Locale.ROOT)) {
case "csv" -> new CsvReportWriter();
case "json" -> new JsonReportWriter();
default -> throw new IllegalArgumentException("Unsupported format: " + format);
};
}
}Running it#
package hub.patterns.factorymethod;
import java.util.List;
public final class FactoryMethodDemo {
public static void main(String[] args) {
List<SalesRow> rows = List.of(new SalesRow("EMEA", 120), new SalesRow("APAC", 75));
// GoF Factory Method: the client picks a creator; the creator picks the product.
List<ReportExporter> exporters = List.of(new CsvReportExporter(), new JsonReportExporter());
for (ReportExporter exporter : exporters) {
ReportExporter.ExportedFile file = exporter.export("q3-sales", rows);
System.out.println("== " + file.name());
System.out.println(file.content());
}
// Simple factory: selection by a runtime value, no subclassing involved.
ReportWriter writer = ReportWriters.forFormat("CSV");
System.out.println("Simple factory chose: " + writer.getClass().getSimpleName());
}
}== q3-sales.csv
region,units
EMEA,120
APAC,75
== q3-sales.json
[{"region":"EMEA","units":120},{"region":"APAC","units":75}]
Simple factory chose: CsvReportWriterStep-by-step walkthrough#
- The creator owns the workflow.
ReportExporter.exportvalidates input, obtains a writer, builds the file name from the writer’s extension and writes the content. It isfinal, so subclasses cannot change the workflow — only the creation step. - The factory method is the single extension point.
createWriter()isprotected abstract. It is not part of the public API; it exists for subclasses. - Concrete creators make one decision each.
CsvReportExporterreturns aCsvReportWriter. Adding XML means addingXmlReportWriterandXmlReportExporter;ReportExporterdoes not change. - The client chooses a creator, not a product.
FactoryMethodDemoworks withReportExporterreferences. It never instantiates a writer. - The simple factory is different.
ReportWriters.forFormatselects a class from a runtime string. There is no subclassing and no deferred decision — it centralises a conditional. That is fine when the choice depends on data, such as a user-selected format.
Advantages and disadvantages#
| Advantages | Disadvantages |
|---|---|
| The creator’s workflow is written once and reused | One creator subclass per product — a parallel class hierarchy |
| New products are added without modifying the creator (OCP) | Relies on inheritance, which fixes the choice at compile time |
| Products can be swapped in tests by subclassing the creator | Overkill when the creator has no workflow of its own |
| Frameworks can call user-supplied creation code at the right moment | Easy to confuse with simple and static factories |
When to use it#
- A base class contains a workflow that needs an object, but cannot know its concrete class.
- You are writing a framework or library and users must plug in their own product types.
- Subclasses already exist for other reasons, and each naturally knows which product it needs.
When not to use it#
- The choice depends on a runtime value (a format string, a configuration key). Use a simple factory, a
Map<String, Supplier<ReportWriter>>, or dependency injection. - There is no shared workflow — creation is all the creator does. Pass a
Supplier<ReportWriter>or the product itself instead. - You need to create families of related objects that must be used together. That is Abstract Factory.
Common implementation mistakes#
- Calling the factory method from the constructor. The subclass is not fully initialised while the superclass constructor runs, so an overridden
createWriter()may see unset fields. Call it lazily from the workflow, asexportdoes. - Making the factory method public. It is an extension point for subclasses, not an API for clients. Keep it
protected. - Leaking concrete types. If clients cast the product to
CsvReportWriter, the abstraction has failed. - A creator with no workflow. A creator whose only method is the factory method is an unnecessary layer; use a
Supplieror a simple factory.
Relationship to SOLID#
- Open/Closed: new products and creators are added without editing
ReportExporter. - Dependency Inversion: the workflow depends on the
ReportWriterabstraction. - Single Responsibility: the workflow and the choice of product are separated into different classes.
- Liskov Substitution: every creator subclass must return a product that honours the
ReportWritercontract, or the shared workflow breaks.
Comparison with similar patterns#
| Pattern | Difference |
|---|---|
| Abstract Factory | An object (not a subclass) creates a family of related products. Abstract Factory is often implemented with several factory methods. |
| Simple factory | One method with a conditional. No inheritance, choice by runtime value. Not GoF. |
| Static factory method | A named alternative to a constructor (Optional.of, Duration.ofSeconds). Not GoF. |
| Builder | Constructs one complex object step by step. Factory Method creates an object in one call. See Builder. |
| Template Method | Factory Method is frequently one step of a template method. |
| Prototype | Creates objects by copying an instance, so it needs no creator hierarchy. |
Real-world uses#
java.util.Collection.iterator(): each collection class decides whichIteratorimplementation to return. Code written againstCollectionuses the iterator without knowing its class.java.net.URLStreamHandler.openConnectionreturns a protocol-specificURLConnection.- In Spring,
@Beanmethods and theFactoryBeaninterface create objects on the container’s behalf. These resemble factory methods. The Patterns in Spring section discusses how closely.
Interview questions and answers#
What is the Factory Method pattern? A creator class declares a method for creating a product and uses it inside its own logic. Subclasses override the method to choose the concrete product. The creator depends only on the product interface.
What is the difference between Factory Method and a simple factory? Factory Method uses inheritance: a subclass decides what to create, and the decision is fixed per subclass. A simple factory is one method that selects a class from its arguments with a conditional. A simple factory is not a GoF pattern.
Is List.of() an example of Factory Method?
No. It is a static factory method — an idiom that replaces a constructor with a named static method. It can return different implementation classes, but no subclass overrides anything.
What is the difference between Factory Method and Abstract Factory? Factory Method creates one product through subclassing. Abstract Factory is an object whose methods create a family of related products; you swap the whole factory object to switch families.
Why should a constructor not call the factory method?
In Java, an overridden method called from a superclass constructor runs before the subclass’s fields are initialised. It can observe default values such as null.
Summary#
- Factory Method defers which class to instantiate to subclasses of a creator.
- The creator usually owns a workflow; the factory method is one step of it.
- Simple factories and static factory methods are useful, but they are different things.
- Prefer composition (
Supplier, DI) when the choice depends on runtime data.
Related topics#
References#
- Gamma, Helm, Johnson, Vlissides. Design Patterns. Addison-Wesley, 1994. Factory Method, p. 107.
- Joshua Bloch. Effective Java, 3rd edition, Item 1: “Consider static factory methods instead of constructors”; Item 19: constructors must not invoke overridable methods.
java.util.Collection, Java SE 21 API.