All 15 Design Patterns in Java questions
More in Design Patterns in Java
Advertisement
Back to results for “Design Patterns in Java”
Java › Design Patterns in Java

What is the Factory Method pattern, and how does it differ from the simpler Static Factory Method idiom (like List.of() or Optional.of())?

Intermediate

Answer

The Factory Method design pattern (Gang of Four) defines an abstract method in a base class that subclasses override to determine which concrete type gets instantiated, deferring instantiation decisions to subclasses as part of a broader class hierarchy design; the more commonly used "static factory method" idiom (a simpler, unrelated convention popularized by Effective Java) is just a static method on a class that returns an instance of that class or a related type (like List.of() or Optional.of()), used primarily for more descriptive naming than a constructor, controlling instance caching/reuse, or returning a subtype without exposing it -- despite the similar name, these are genuinely distinct concepts serving different structural purposes.
// GoF Factory Method pattern: subclasses decide the concrete type
abstract class DocumentCreator {
    abstract Document createDocument();  // subclasses override to return different Document types
}
class PdfCreator extends DocumentCreator {
    Document createDocument() { return new PdfDocument(); }
}

// Static factory method idiom: just a descriptively-named static creation method
public class Point {
    public static Point of(int x, int y) { return new Point(x, y); }  // more readable than 'new Point(x, y)'
}
Real-world example A document processing library uses the true GoF Factory Method pattern (an abstract createDocument() overridden by PdfCreator, WordCreator, etc.) to let each concrete creator subclass determine its own document type, while a separate, unrelated utility class simply exposes a static factory method Point.of(x, y) purely for more readable object construction syntax.

Common follow-ups: What are the specific benefits static factory methods have over public constructors, according to Effective Java?;When would you actually need the full GoF Factory Method pattern versus just a simpler static factory method?