Creational PatternsFactory Method PatternEasy⏱️ ~2 min

What is the Factory Method Pattern?

Definition
Factory Method Pattern is a creational design pattern that defines an interface for creating objects but lets subclasses decide which class to instantiate. The factory method lets a class defer instantiation to subclasses.
Problem It Solves:

When a class cannot anticipate the exact type of objects it needs to create, the Factory Method Pattern provides a way to delegate the object creation logic to subclasses. This is particularly useful when the creation logic is complex or when the system needs to be independent of how its objects are created and composed.

Core Intent:

First, separate object creation from object usage. Second, allow subclasses to alter the type of objects that will be created without changing the client code. Third, promote loose coupling by reducing the dependency on concrete classes.

Interview Tip: Always emphasize that Factory Method is about "defining an interface" for creation. The key difference from Simple Factory is that Factory Method uses inheritance and lets subclasses decide the concrete type.
When NOT to Use:

If you only have one concrete product type and no variation is expected, Factory Method adds unnecessary complexity. In such cases, direct instantiation is simpler and more appropriate. Use Factory Method only when you anticipate multiple product variants or when subclasses need to customize object creation.

💡 Key Takeaways
Defines an interface for creating objects but delegates instantiation to subclasses
Promotes loose coupling by removing direct dependencies on concrete classes
Uses inheritance as the mechanism for object creation variation
Different from Simple Factory which uses a single factory class with conditional logic
📌 Examples
1A document editor that creates different document types (PDF, Word, Text) based on user choice
2A logistics app where different transport types (Truck, Ship, Plane) are created by region-specific factories
← Back to Factory Method Pattern Overview