GoF pattern • Creational
GoFCreationalJava example
Factory Method solves a specific structural problem in the design.
Let subclasses decide which concrete product to create.
Pattern overview
GoF pattern
Let subclasses decide which concrete product to create.
Intent
Define an interface for creating an object while letting subclasses choose the concrete implementation.
Problem
A framework or base class needs extension points for object creation without embedding all creation decisions itself.
Solution
Expose a creation hook that subclasses override to provide the appropriate concrete product.
Fit and tradeoffs
FamilyGoF
CategoryCreational
Best used when
- When a base workflow stays fixed but a product type varies.
- When you are writing a framework or template-style class.
Tradeoffs
- Relies on subclassing, which can couple variation to inheritance.
- Not ideal when many product dimensions vary at once.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
abstract class ReportExporter {
public final String export() {
Formatter formatter = createFormatter();
return formatter.format("Quarterly revenue");
}
protected abstract Formatter createFormatter();
}
interface Formatter {
String format(String content);
}
final class PdfExporter extends ReportExporter {
protected Formatter createFormatter() {
return content -> "PDF:" + content;
}
}