Command Palette

Search for a command to run...

PHASE 2Beginner ~7 min· topic 1 of 22Creational

Creational 1 — Factory

In one line

Centralize object creation behind one method so callers depend on the created type's contract, not its construction logic.

0/22 · 0%

Think of it like this

A pizza counter. You say 'one Margherita' and get a pizza. You don't knead the dough or know the recipe; the kitchen (factory) decides how to make it.

Key ideas

  1. 01

    Problem solved: callers scattered with if/else constructor logic; adding a type means touching many files.

  2. 02

    Factory Method: one abstract create() per hierarchy. Abstract Factory: a family of related products.

  3. 03

    In interviews, a simple static factory (sometimes over 'abstract factory') is usually the right size.

  4. 04

    Java note: Calendar.getInstance(), NumberFormat.getInstance(), List.of() and Executors.newFixedThreadPool() are static factory methods.

  5. 05

    Registry variant: a Map<Type, Supplier<Product>> lets new types register themselves, so even the factory stays closed to modification.

Java / Spring map

  • →

    Spring's @Bean methods / FactoryBean are factories; @Configuration classes are factory classes.

Code & diagrams

VehicleFactory.javajava

Simple factory: zero switch statements in callers.

public interface Vehicle { String type(); }

public class Car implements Vehicle { public String type() { return "CAR"; } }
public class Bike implements Vehicle { public String type() { return "BIKE"; } }
public class Truck implements Vehicle { public String type() { return "TRUCK"; } }

public final class VehicleFactory {
  public static Vehicle create(String type) {
    return switch (type.toUpperCase()) {
      case "CAR"   -> new Car();
      case "BIKE"  -> new Bike();
      case "TRUCK" -> new Truck();
      default      -> throw new IllegalArgumentException("unknown: " + type);
    };
  }
}
// Parking lot gate: Vehicle v = VehicleFactory.create(plate); // new vehicle → one line.

Explain without notes

01

Which OCP violation does the factory prevent?

Practice

01

Add 'BUS' and 'EV' variants to the factory without touching callers.

Trade-offs

  • ↔

    A factory hides which concrete class is used — good for decoupling, bad when callers need type-specific behavior.

Completion checklist

  • I can explain intent + one real use.

  • I can distinguish a simple static factory, Factory Method, and Abstract Factory.

Back to phase