What is the Factory pattern in Java?
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.
Previous
What is the Builder design pattern in Java?
Next
What is the Observer design pattern in Java?