What is the Factory design pattern?
The Factory pattern encapsulates object creation behind a method or class, so callers request objects by type or configuration without depending on concrete class names or constructors. This decouples the consuming code from the instantiation details, making the system easier to extend and test.
There are two GoF-recognized factory patterns. Factory Method defines a method (typically abstract) in a superclass or interface for creating an object, and subclasses override it to return different concrete types. The creator class is extended to vary the product. Abstract Factory provides an interface for creating families of related objects — multiple factory methods grouped together — so entire product families can be swapped by substituting the factory implementation.
In practice, many Java codebases use Simple Factory — a static or instance method that takes a parameter and returns the appropriate subtype — which is not an official GoF pattern but is extremely common. NumberFormat.getInstance(locale) and Calendar.getInstance() in the JDK are examples of this style.
The key benefit is the Open/Closed Principle: you can add new product types by adding a new subclass or factory implementation without modifying existing calling code. The caller only depends on the product interface, not the concrete product.
For testing, factory methods make it straightforward to substitute a test factory that returns mocks or in-memory implementations instead of real ones — without changing the code under test.
Common implementation in Java: an interface or abstract class defines the product contract; a factory class or method takes a string, enum, or configuration object and instantiates the correct concrete implementation using a switch or map; the caller receives the product typed as the interface.
When combined with Dependency Injection, factories are often injected themselves, allowing even the factory strategy to be swapped at configuration time.
Explains the core idea of encapsulating creation and decoupling from concrete types, and names Factory Method vs. Simple Factory or Abstract Factory.
Distinguishes Factory Method from Abstract Factory precisely, gives JDK examples, explains Open/Closed benefit, and mentions testability advantage.
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