What is the Factory pattern and when would you use it?
The Factory pattern is a creational design pattern that encapsulates object creation logic behind an interface, so callers don't need to know which concrete class they're instantiating. The term covers two related patterns: Factory Method (a method that subclasses override to produce objects) and Abstract Factory (an interface for creating families of related objects).
The core problem it solves: when you write `new ConcreteClass()` throughout a codebase, you've hardcoded a dependency on that specific class. If the class changes, or you need to swap in a different implementation (different database driver, different payment provider, different notification channel), you must find and change every instantiation site. A factory centralizes that decision.
A practical example: an application supports multiple notification channels — email, SMS, Slack. Rather than scattering `if channel == 'email': return EmailNotifier()` logic throughout the codebase, a `NotifierFactory.create(channel)` method owns that conditional. Callers only work with the `Notifier` interface. Adding push notifications means touching one file.
When to use it: when the type to create is determined at runtime (from config, user input, or a strategy name); when you want to isolate object construction from business logic for testability; when constructing an object is complex enough that you want to hide the details; and when you anticipate needing to swap implementations. It pairs naturally with dependency injection — factories are often what DI containers call to build objects.
Abstract Factory extends this: instead of creating one type of object, it creates a family. A UI toolkit factory might produce buttons, checkboxes, and dialogs that all share a visual theme. Swapping the factory swaps the entire family consistently.
A Python-idiomatic approach often skips the class entirely and uses a dictionary mapping strings to classes, or a registration pattern where subclasses register themselves. This achieves the same decoupling without ceremony.
The tradeoff: factories add a layer of indirection. For simple, stable object creation that will never change, they add complexity without value. Use them when variability is real, not hypothetical.
Correctly explains the pattern's intent and the problem it solves (decoupling callers from concrete types), gives a concrete use case, and distinguishes Factory Method from just using a constructor.
All of the above plus: distinguishes Factory Method from Abstract Factory, discusses when NOT to use it, mentions testability benefits, and covers a language-idiomatic approach (e.g., registry pattern in Python).
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment