Factory Method Pattern Basics
What you'll learn: How to delegate object creation decisions to subclasses through a flexible, extensible interface.
The Core Problem
Imagine you're building a logistics app that manages truck delivery. Later, you want to add ship delivery. If you hard-code new Truck() everywhere, you'll need to change code in dozens of places. The Factory Method pattern solves this by centralizing creation logic.
How It Works
Instead of calling constructors directly, you define a factory method — an interface or abstract method that returns objects. Subclasses override this method to decide which concrete class to instantiate.
The key players:
- Creator (abstract) — declares the factory method
- Concrete Creators — implement the method, returning specific product types
- Product (interface) — common interface for all objects the factory creates
- Concrete Products — actual implementations
Plain-English Analogy
Think of a restaurant menu system. The Restaurant class has an abstract createDish() method. ItalianRestaurant overrides it to return Pizza, while JapaneseRestaurant returns Sushi. The client code just calls createDish() without knowing whether it gets pizza or sushi — the subclass decides.
Why Use It?
- Decoupling: Client code doesn't depend on concrete classes
- Extensibility: Add new product types without modifying existing code
- Single Responsibility: Creation logic lives in one place per product family
You've already seen the Singleton pattern control how many instances exist. Factory Method controls which class gets instantiated.
Key Takeaway: Factory Method defines a creation interface but lets subclasses choose the concrete class, making your code flexible and extension-friendly.