Low-Level Design Tutorial 0/42 lessons ~6 min read Lesson 22

    Factory Pattern

    Factory patterns encapsulate object creation — hiding whether you construct Car, Truck, or future Scooter.

    Course progress0%
    Focus
    9 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. Client requests object by key or enum.
    2. Factory validates input and chooses implementation.
    3. Returns interface type hiding concrete class.
    4. Register new types without editing client.
    5. Throw meaningful error for unknown type.
    6. Inject factory when testing with stub products.

    Informative example

    Vehicle factory with sealed hierarchy and exhaustive switch:

    java
    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

    Q1BeginnerWhat problem does Factory solve?
    Encapsulates creation logic and decouples clients from concrete classes.
    Q2BeginnerFactory Method vs Simple Factory?
    Simple Factory is one creator method; Factory Method uses inheritance — subclass creates product.
    Q3IntermediateHow does factory support OCP?
    Add product + registration without changing client creation call pattern.
    Q4IntermediateFactory vs Builder?
    Factory chooses among fully built products; Builder assembles complex object stepwise.
    Q5AdvancedDesign factory for chess pieces.
    PieceFactory.create(PieceType, Color) returns Piece interface; each piece class encapsulates move rules.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.