Factory Method: Parameterized Creation
You'll learn how to use parameters to let a factory method decide which concrete class to instantiate at runtime.
The Core Idea
In the basic Factory Method pattern, each factory subclass returns a specific type of product. But what if you want one factory method to create different product types based on input? That's where parameterized creation comes in.
Instead of hardcoding which class to instantiate, you pass a parameter (like a string, enum, or configuration object) to the factory method. The method examines that parameter and uses conditional logic to decide which concrete class to create.
Plain-English Analogy
Imagine ordering at a coffee shop. Instead of going to separate counters for "Espresso Factory" and "Latte Factory," you go to one counter and say "I want an espresso" or "I want a latte." The barista (factory method) listens to your parameter and makes the appropriate drink.
Why It Matters
This approach centralizes object creation logic in one place while still providing flexibility. You can add new product types by extending the conditional logic without changing calling code—just pass a different parameter.
The trade-off? Your factory method becomes more complex with conditional branches. You must balance convenience against maintainability.
Example Structure (Conceptual)
You might have a factory method like:
- Input: A parameter identifying the desired product type
- Processing: Conditional logic (if/switch) examining the parameter
- Output: An instance of the appropriate concrete class
The client calls the factory with different parameters to get different objects, all through the same interface.
Key Takeaway: Parameterized factory methods use runtime inputs to select which concrete class to instantiate, centralizing creation logic while maintaining flexibility.