Factory Pattern
Factory patterns encapsulate object creation — hiding whether you construct Car, Truck, or future Scooter.
Introduction
Factory patterns encapsulate object creation — hiding whether you construct Car, Truck, or future Scooter. Simple Factory, Factory Method, and Abstract Factory differ in complexity; interviews usually want Factory Method or registry-based Simple Factory.
Factories support OCP: add new vehicle type by registering new factory without editing client. They also centralize validation when constructing valid objects is non-trivial.
Pair factories with interfaces returned to callers.
Understanding the topic
Key concepts
- Simple Factory: one class creates based on parameter.
- Factory Method: subclass decides which product to create.
- Abstract Factory: families of related products.
- Registry maps type codes to suppliers (Function, Supplier).
- Creation logic separate from business logic (SRP).
- Java 21: switch on sealed types for exhaustive factories.
Step-by-step explanation
- Client requests object by key or enum.
- Factory validates input and chooses implementation.
- Returns interface type hiding concrete class.
- Register new types without editing client.
- Throw meaningful error for unknown type.
- Inject factory when testing with stub products.
Informative example
Vehicle factory with sealed hierarchy and exhaustive switch:
public sealed interface Vehicle permits Car, Truck, Motorcycle {SpotType requiredSpotType();record Car(String plate) implements Vehicle {public SpotType requiredSpotType() { return SpotType.COMPACT; }}record Truck(String plate) implements Vehicle {public SpotType requiredSpotType() { return SpotType.LARGE; }}record Motorcycle(String plate) implements Vehicle {public SpotType requiredSpotType() { return SpotType.BIKE; }}}public final class VehicleFactory {public Vehicle create(VehicleType type, String plate) {return switch (type) {case CAR -> new Vehicle.Car(plate);case TRUCK -> new Vehicle.Truck(plate);case MOTORCYCLE -> new Vehicle.Motorcycle(plate);};}}public enum VehicleType { CAR, TRUCK, MOTORCYCLE }
Sealed + switch documents all variants — compiler helps when adding new VehicleType.
Real-world use
Real-world applications
- Creating payment handlers, chess pieces, UI components.
- Parsing user input into domain objects.
- Hiding construction complexity (valid invariants).
Best practices
- Return interface or sealed supertype from factory.
- Keep factory free of business workflow logic.
- Use enum keys for fixed variant sets.
- Validate parameters before construction.
- Document extension registration process.
Common mistakes
- God factory knowing entire application graph.
- Returning concrete types forcing client coupling.
- Factory with business rules beyond creation.
- Abstract Factory when Simple Factory suffices.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat problem does Factory solve?+
Answer
2BeginnerQuestionFactory Method vs Simple Factory?+
Answer
3IntermediateQuestionHow does factory support OCP?+
Answer
4IntermediateQuestionFactory vs Builder?+
Answer
5AdvancedQuestionDesign factory for chess pieces.+
Answer
Summary
Factories encapsulate object creation. Return abstractions to clients. Registry or switch supports new variants. Separate creation from business orchestration. Match factory complexity to problem scope.