1. The Problem: The "New" keyword spread
If your code is full of if (type == A) return new ServiceA(), your client code becomes tightly coupled to the concrete classes. Every time a new service is added, you must hunt down all occurrences of new and update them.
2. The Solution: Simple Factory
A factory centralizes the creation logic in one place.
The Implementation
public class NotificationFactory {
public Notification create(String type) {
if (type.equals("SMS")) return new SMSNotification();
if (type.equals("Email")) return new EmailNotification();
throw new IllegalArgumentException("Unknown type");
}
}
3. Advanced: Factory Method Pattern
Instead of one factory class with if-else, we let subclasses decide which object to create. This is the "True" GoF pattern.
public abstract class NotificationCreator {
public abstract Notification create();
// Core logic that uses the notification
public void send() {
Notification n = create();
n.deliver();
}
}
4. Real-world Intuition: The Pizza Shop
You don't care how the pizza is made or what brand of oven is used. You just call the "Kitchen" (The Factory) and ask for a "Pepperoni Pizza." The kitchen handles the ingredients and the specific cooking class.
5. Interview Discussion
- Trade-offs: Simple Factory violates OCP (you still modify the factory class). Factory Method follows OCP but is more complex.
- Dependency Injection: In modern frameworks like Spring, the
ApplicationContextacts as a giant factory for all your beans.
Final Takeaway
The Factory pattern is about Hiding Complexity. The user should never see the new keyword for complex service objects.