When to use Factory pattern — appropriate use cases
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
You use Factory when the exact class you need depends on runtime data.
For example, in a notification service the user can choose email, SMS, or push, and that preference lives in the database. You can't hardcode new EmailNotifier everywhere, because tomorrow the same user might switch to SMS. A factory lets you pass the preference and get back the right notifier.
The second reason is complex creation. Say you're building a database connection that needs a pool, timeout settings, SSL config, and credentials. Doing that inline every time is repetitive and error-prone, so a factory hides it behind a single create method.
The third reason is the Open Closed Principle: when you add a new payment method like cryptocurrency, you add a class and a case in the factory, and the order service that calls the interface never changes. But there's a real trade-off — Factory adds indirection. When you see a PaymentProcessor variable, you can't tell at a glance whether it's Stripe or PayPal without tracing the factory.
So I don't use Factory for simple objects. If I'm creating a DTO like new UserDto with an id and name, I just use new — a factory there is pure overhead. The rule of thumb is: use Factory when the type varies at runtime or creation is complex, and otherwise keep it simple.
Two mistakes freshers make are using Factory everywhere because they read it's a best practice, and introducing it too early before there's any real variation. I'd follow YAGNI — wait until I actually feel the pain of hardcoded types or duplicated creation code, then refactor to a factory.
When to use Factory pattern — appropriate use cases
Direct Answer
Reach for Factory when the concrete type depends on runtime data (pick a processor by country), when creation is complex (pools, timeouts, SSL), or when you want to add types without editing callers (OCP). Skip it for simple, stable objects — wrapping a DTO in a factory is needless indirection that violates YAGNI.
Common Mistakes & Pitfalls
- Factory everywhere. Wrapping every
newin a factory, even DTOs, adds indirection and hurts readability. - Introducing it too early. Follow YAGNI — wait for duplicated creation code or real type variation before refactoring.
- Confusing Factory with Service Locator. Pulling beans from the context inside a 'factory' is the Service Locator anti-pattern; prefer DI to wire dependencies.
- Hiding business logic in the factory. A factory should create and wire, not run operations.
Check your understanding
Answer these without looking back at the article.
- When does using a Factory add unnecessary complexity?
- How does Factory work with the Strategy pattern?
- What is the difference between Factory and the Service Locator anti-pattern?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.