☕ Java Advanced

What is the Factory pattern in Java?

Why Interviewers Ask This

Senior Java engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.

Answer

The Factory pattern provides an interface for creating objects while allowing subclasses or implementations to decide which class to instantiate. It decouples object creation from the code that uses the objects. The Factory Method pattern defines an interface for creating an object but lets subclasses decide the concrete class. The Abstract Factory creates families of related objects. Example: ShapeFactory.createShape("circle") returns a Circle without the caller knowing the concrete type. In Java, static factory methods are common: Integer.valueOf(), List.of(), Optional.of(). Advantages: encapsulates object creation logic, makes code more testable by allowing mock factories, and supports the Open/Closed Principle.

Pro Tip

This topic has Java-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.