Define an interface for creating objects, but let subclasses decide which class to instantiate. The exact concrete type is decided at runtime. You
Factory Method
Overview
Define an interface for creating objects, but let subclasses decide which class to instantiate.
When to use
- The exact concrete type is decided at runtime.
- You want to decouple creation logic from usage.
Java example
TypeScript example
Pros and cons
Pros:
- Centralizes creation logic.
- Enables substitution of product types.
Cons:
- Adds extra classes.
- Can be overkill for simple creation.
Common pitfalls
- Returning different product types from the same factory.
- Pushing too much logic into the factory.