Factory Method vs Direct Instantiation
You'll learn: When to delegate object creation to a factory method instead of calling constructors directly, and why this extra layer can make your code more flexible.
The Core Difference
When you create an object, you have two basic choices:
Direct Instantiation means calling a constructor yourself:
Car myCar = new Car("sedan");
Factory Method means asking a method to create the object for you:
Car myCar = carFactory.createCar("sedan");
At first glance, the factory approach seems like extra work. Why add a middleman? But that "middleman" gives you flexibility.
When Direct Instantiation Works Fine
If you know exactly what type you need and it won't change, direct instantiation is perfectly acceptable. It's simple, clear, and has no unnecessary indirection. The KISS principle applies here.
When Factory Methods Shine
Factory methods become valuable when:
- You need runtime decisions: The factory can choose which concrete class to instantiate based on parameters or configuration
- Construction is complex: The factory encapsulates multi-step setup logic
- You want to change implementations later: Clients depend on the factory interface, not specific constructors—supporting the Dependency Inversion Principle
- You need testability: A factory can be swapped with a test double; you can't swap
new
Think of it like ordering food: you could cook directly (instantiation), or you could ask a chef (factory method). If you're making toast, cooking is fine. If you need a meal that varies by season, dietary needs, and available ingredients, delegation to the chef provides flexibility.
The Trade-off
Factory methods add abstraction. Use them when you need the flexibility to vary what gets created, not just how existing objects are configured.
Key Takeaway: Factory methods trade directness for flexibility—use them when object creation needs to vary or when hiding construction complexity improves maintainability.