Java › Design Patterns in Java
What is the Factory Method pattern's simplest form -- a basic static factory returning different subtype instances based on input -- and why might you prefer it over exposing constructors directly?
BeginnerAnswer
A simple factory encapsulates object creation logic behind a single method (often static) that decides which concrete subtype to instantiate based on input parameters, hiding the specific subclasses entirely from calling code -- this is useful when the calling code shouldn't need to know or care about the specific implementation class being used, only the common interface/supertype, and centralizes creation logic in one place rather than scattering constructor calls (and the subtype-selection logic they'd otherwise require) throughout the codebase.
public interface Shape { double area(); }
class Circle implements Shape { /* ... */ }
class Square implements Shape { /* ... */ }
public class ShapeFactory {
public static Shape create(String type, double size) {
return switch (type) {
case "circle" -> new Circle(size);
case "square" -> new Square(size);
default -> throw new IllegalArgumentException("Unknown shape: " + type);
};
}
}Real-world example A drawing application reads shape type names from a configuration file and uses a simple ShapeFactory.create() method to instantiate the correct Shape subtype, keeping the mapping between configuration strings and concrete classes centralized in one place rather than scattered across the codebase wherever a shape needs to be created.