SyntaxPilot
Courses/Low-Level Design/Lesson 23

Low-Level Design · Lesson 23 of 90 · 11 min

Simple Factory and Factory Method

Simple Factorystatic factory methodnaming factory methods (of, from, valueOf)Factory Method patternproductconcrete productcreatorconcrete creatorparameterized factoryregistry-based factoryfactories and OCP

These are the notes for Low-Level Design (LLD) episode 23. Last episode, Singleton controlled how many objects exist; today's patterns control which object gets created, and where that decision lives. We start with a delivery app that delivers by cycle but charges the bike price, invent the Simple Factory (a parameterized factory), see why static factory methods beat constructors (names like of, from, valueOf, and the famous Integer.valueOf(127) cache), build the Gang of Four Factory Method pattern with its four roles (product, concrete product, creator, concrete creator), and finish with a registry-based factory that follows the open-closed principle. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs and error messages are real.

1. The real-life idea: ordering at a dosa counter

At a dosa counter in Chennai you say "one masala dosa". You say what you want; you don't walk into the kitchen and pour the batter yourself. The kitchen is the one place that knows how: batter, tawa, filling. If the recipe changes, only the kitchen changes. You get a plate and just eat it.

In code, a factory is that kitchen: the one place that knows how to create objects. The object it hands back is the product, and you use it through its interface without knowing its exact class.

At the counter In code
"One masala dosa" A request: a type name or a parameter
The kitchen A factory: the one place that knows how to create
The plate The product: an object you use through its interface

2. The problem in code: the creation decision is copied

Ramesh runs a delivery app in Pune. A Vehicle interface has a rate in rupees per km. A default method (episode 3) gives every vehicle its class name. The order screen and the price screen each decide the vehicle with their own if-else. Then Ramesh adds cycles for parcels up to 2 kg: he updates the order screen and forgets the price screen.

interface Vehicle {
    int perKm();                                     // rupees per km
    default String name() { return getClass().getSimpleName(); }
}
class Cycle implements Vehicle { public int perKm() { return 4; } }
class Bike implements Vehicle { public int perKm() { return 8; } }
class Van implements Vehicle { public int perKm() { return 20; } }

public class Main {
    public static void main(String[] args) {
        int kg = 1;                                  // a 1 kg birthday cake
        Vehicle forOrder;                            // order screen decides...
        if (kg <= 2) forOrder = new Cycle();         // new type added here
        else if (kg <= 10) forOrder = new Bike();
        else forOrder = new Van();
        Vehicle forQuote;                            // ...price screen decides again
        if (kg <= 10) forQuote = new Bike();         // forgot Cycle here
        else forQuote = new Van();
        System.out.println("Delivered by " + forOrder.name());
        System.out.println("Quote: Rs " + forQuote.perKm() + "/km (" + forQuote.name() + ")");
    }
}
Delivered by Cycle
Quote: Rs 8/km (Bike)

The cake goes by cycle, but the customer is quoted (and overcharged) the bike rate. The compiler said nothing.

Why it broke

  • The decision "which class to create" is copied into every screen (and tomorrow the invoice screen too).
  • Every copy names the concrete classes (Cycle, Bike, Van). A concrete class is a real class you can call new on, unlike an interface or abstract class.
  • A new vehicle means finding and editing every copy. Miss one and you get a wrong answer, no error.

What we want: one place decides; everyone else just asks.

You can't just new the interface

interface Vehicle { String name(); int perKm(); }
public class Main {
    public static void main(String[] args) {
        Vehicle v = new Vehicle();               // "just give me a vehicle"
        System.out.println(v.name());
    }
}
Main.java:4: error: Vehicle is abstract; cannot be instantiated
        Vehicle v = new Vehicle();               // "just give me a vehicle"
                    ^
1 error

An interface has no objects of its own; somebody has to pick a concrete class. That somebody should be a factory.

3. The Simple Factory

interface Vehicle {
    int perKm();                                     // rupees per km
    default String name() { return getClass().getSimpleName(); }
}
class Cycle implements Vehicle { public int perKm() { return 4; } }
class Bike implements Vehicle { public int perKm() { return 8; } }
class Van implements Vehicle { public int perKm() { return 20; } }

class VehicleFactory {                               // the ONE place that decides
    static Vehicle forWeight(int kg) {
        if (kg <= 2) return new Cycle();
        if (kg <= 10) return new Bike();
        if (kg <= 500) return new Van();
        throw new IllegalArgumentException("no vehicle for " + kg + " kg");
    }
}
public class Main {
    public static void main(String[] args) {
        for (int kg : new int[]{1, 6, 80}) {
            Vehicle order = VehicleFactory.forWeight(kg);   // order screen
            Vehicle quote = VehicleFactory.forWeight(kg);   // price screen
            System.out.println(kg + " kg: " + order.name() + ", Rs " + quote.perKm() + "/km");
        }
        VehicleFactory.forWeight(900);                      // a piano?
    }
}
1 kg: Cycle, Rs 4/km
6 kg: Bike, Rs 8/km
80 kg: Van, Rs 20/km
Exception in thread "main" java.lang.IllegalArgumentException: no vehicle for 900 kg
    at VehicleFactory.forWeight(Main.java:14)
    at Main.main(Main.java:24)
  • VehicleFactory.forWeight holds the whole decision, once. Both screens ask it, so they always agree.
  • It returns the interface type (Vehicle), so callers never depend on Bike or Van.
  • For an impossible weight it throws a clear IllegalArgumentException instead of quietly returning a wrong vehicle: fail loudly and early.

Vocabulary:

  • Simple Factory: one class (often one static method) whose only job is to create objects.
  • Parameterized factory: a factory where a parameter (here the weight; often a type name or an enum) decides which product comes out.
  • The Simple Factory is not one of the Gang of Four's 23 patterns. It's a popular idiom and the first step towards the real factory patterns.

4. Static factory methods

A static factory method is a static method that creates and returns an object, used instead of (or as well as) a constructor. Constructors always have the class's name, so they can't say what their arguments mean, and two constructors can't take the same parameter types:

class Money {
    private final long paise;
    Money(int rupees) { this.paise = rupees * 100L; }   // Money(250) = Rs 250
    Money(int paise) { this.paise = paise; }            // Money(250) = 250 paise?
    public String toString() { return String.format("Rs %.2f", paise / 100.0); }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(new Money(250));
    }
}
Main.java:4: error: constructor Money(int) is already defined in class Money
    Money(int paise) { this.paise = paise; }            // Money(250) = 250 paise?
    ^
1 error

With static factory methods and a private constructor, the name says exactly what the number means:

class Money {
    private final long paise;
    private Money(long paise) { this.paise = paise; }
    static Money ofRupees(int rupees) { return new Money(rupees * 100L); }   // named
    static Money fromPaise(long paise) { return new Money(paise); }          // named
    public String toString() { return String.format("Rs %.2f", paise / 100.0); }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(Money.ofRupees(250));
        System.out.println(Money.fromPaise(250));
    }
}
Rs 250.00
Rs 2.50

Naming conventions (Effective Java, Item 1)

Name Meaning JDK example
from Convert a single value into this type Date.from(instant)
of Build from several values List.of(a, b, c), EnumSet.of(...), LocalDate.of(y, m, d)
valueOf Longer form of from / of String.valueOf(42), Integer.valueOf(7), BigInteger.valueOf(...)
instance / getInstance Returns an instance, maybe the same one each time StackWalker.getInstance(...), a Singleton
create / newInstance Always a new instance Array.newInstance(type, length)
getType Like getInstance, but in another class Files.getFileStore(path)
newType Like newInstance, but in another class Files.newBufferedReader(path)
type Short form of getType / newType Collections.list(...)

Advantages over constructors: they have names, they can return an existing object instead of always a new one, they can return any subtype of the declared return type (so the real class stays hidden), and the returned class can depend on the arguments. The cost: a class whose only constructors are private can't be subclassed.

The Integer.valueOf cache

import java.util.*;
import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        List<String> stops = List.of("Baner", "Aundh", "Pashan");   // of: from several values
        LocalDate due = LocalDate.of(2026, 11, 3);              // of: from parts
        String count = String.valueOf(42);                          // valueOf: convert
        System.out.println(stops + " " + due + " " + count);

        Integer a = Integer.valueOf(127), b = Integer.valueOf(127);
        Integer c = Integer.valueOf(128), d = Integer.valueOf(128);
        System.out.println("127 same object? " + (a == b));
        System.out.println("128 same object? " + (c == d));
        System.out.println("128 equal value? " + c.equals(d));
    }
}
[Baner, Aundh, Pashan] 2026-11-03 42
127 same object? true
128 same object? false
128 equal value? true

The Integer.valueOf(int) Javadoc says: "This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range." So for 127 it returns the same saved object both times (== is true), while for 128 it makes two objects (== is false), though their values are equal. A constructor could never reuse an object; a factory method can. Lesson: compare values with equals(), never with ==.

5. The Factory Method pattern

Ramesh opens a hill branch near Shimla. Deliveries follow exactly the same steps (plan route, pick up, deliver), but the roads are steep, so it must be a jeep. Copying the whole flow for each branch is copy-paste again. Instead: write the flow once and leave one gap: which vehicle to create. Each branch fills only that gap.

interface Vehicle {
    int perKm();                                     // rupees per km
    default String name() { return getClass().getSimpleName(); }
}
class Cycle implements Vehicle { public int perKm() { return 4; } }
class Bike implements Vehicle { public int perKm() { return 8; } }
class Van implements Vehicle { public int perKm() { return 20; } }
class Jeep implements Vehicle { public int perKm() { return 25; } }

abstract class DeliveryService {                     // CREATOR
    abstract Vehicle createVehicle();                // the factory method
    String deliver(String item) {                    // shared steps, one copy
        Vehicle v = createVehicle();                 // subclass decides WHICH
        return item + " by " + v.name() + " at Rs " + v.perKm() + "/km";
    }
}
class CityDelivery extends DeliveryService {         // CONCRETE CREATOR
    Vehicle createVehicle() { return new Bike(); }
}
class HillDelivery extends DeliveryService {         // CONCRETE CREATOR
    Vehicle createVehicle() { return new Jeep(); }   // steep roads
}
public class Main {
    public static void main(String[] args) {
        DeliveryService[] services = { new CityDelivery(), new HillDelivery() };
        for (DeliveryService s : services) System.out.println(s.deliver("Cake"));
    }
}
Cake by Bike at Rs 8/km
Cake by Jeep at Rs 25/km
  • DeliveryService is an abstract class (episode 3): a class with a gap that subclasses must fill. The gap is the abstract method createVehicle(): the factory method.
  • deliver() contains the shared steps once and calls createVehicle() whenever it needs a vehicle.
  • CityDelivery and HillDelivery override createVehicle() (episode 8) to choose Bike and Jeep.

Forgetting to fill the gap is a compile error:

interface Vehicle {
    int perKm();                                     // rupees per km
    default String name() { return getClass().getSimpleName(); }
}
class Cycle implements Vehicle { public int perKm() { return 4; } }
class Bike implements Vehicle { public int perKm() { return 8; } }
class Van implements Vehicle { public int perKm() { return 20; } }
class Jeep implements Vehicle { public int perKm() { return 25; } }

abstract class DeliveryService {                     // CREATOR
    abstract Vehicle createVehicle();                // the factory method
    String deliver(String item) {                    // shared steps, one copy
        Vehicle v = createVehicle();                 // subclass decides WHICH
        return item + " by " + v.name() + " at Rs " + v.perKm() + "/km";
    }
}
class CityDelivery extends DeliveryService {         // CONCRETE CREATOR
    Vehicle createVehicle() { return new Bike(); }
}
class HillDelivery extends DeliveryService {         // CONCRETE CREATOR
    // forgot createVehicle()
}
public class Main {
    public static void main(String[] args) {
        DeliveryService[] services = { new CityDelivery(), new HillDelivery() };
        for (DeliveryService s : services) System.out.println(s.deliver("Cake"));
    }
}
Main.java:20: error: HillDelivery is not abstract and does not override abstract method createVehicle() in DeliveryService
class HillDelivery extends DeliveryService {         // CONCRETE CREATOR
^
1 error

The four roles

The Gang of Four intent: "Define an interface for creating an object, but let subclasses decide which class to instantiate."

Role Meaning In our code
Product The type of object being created Vehicle
Concrete product A real class that implements the product Bike, Jeep
Creator Declares the factory method and uses it in its own logic DeliveryService (abstract)
Concrete creator Overrides the factory method to choose a concrete product CityDelivery, HillDelivery
   «creator» DeliveryService ───uses───▶ «interface» Vehicle   (product)
     + createVehicle(): Vehicle  (abstract)        ▲
     + deliver(item): String                       ┆ implements
              ▲                                    ┆
              │ extends                            ┆
   HillDelivery (concrete creator) ──creates──▶  Jeep (concrete product)

Note: "factory method" (lower case) also loosely means any method that creates objects; "the Factory Method pattern" specifically means this creator/subclass structure.

6. A registry-based factory and the open-closed principle

Our Simple Factory still breaks the open-closed principle (episode 13: open for extension, closed for modification): every new vehicle means editing its if-else. The fix is a registry: a lookup table from a name to a maker. A Supplier<T> (episode 5) is a function that takes nothing and returns a T; Bike::new is a method reference meaning "a function that calls new Bike()".

import java.util.*;
import java.util.function.Supplier;

interface Vehicle {
    int perKm();                                     // rupees per km
    default String name() { return getClass().getSimpleName(); }
}
class Bike implements Vehicle { public int perKm() { return 8; } }
class Van implements Vehicle { public int perKm() { return 20; } }
class VehicleRegistry {
    private static final Map<String, Supplier<Vehicle>> makers = new HashMap<>();
    static void register(String type, Supplier<Vehicle> maker) { makers.put(type, maker); }
    static Vehicle create(String type) {
        Supplier<Vehicle> maker = makers.get(type);
        if (maker == null) throw new IllegalArgumentException("unknown vehicle: " + type);
        return maker.get();                          // call the stored "new"
    }
}
class Drone implements Vehicle { public int perKm() { return 30; } }
public class Main {
    public static void main(String[] args) {
        VehicleRegistry.register("bike", Bike::new);
        VehicleRegistry.register("van", Van::new);
        VehicleRegistry.register("drone", Drone::new);   // NEW type: factory untouched
        for (String t : List.of("bike", "drone", "van"))
            System.out.println(t + " -> " + VehicleRegistry.create(t).name());
        VehicleRegistry.create("rocket");
    }
}
bike -> Bike
drone -> Drone
van -> Van
Exception in thread "main" java.lang.IllegalArgumentException: unknown vehicle: rocket
    at VehicleRegistry.create(Main.java:15)
    at Main.main(Main.java:27)

Drone was registered from outside and VehicleRegistry was not touched: the factory is closed for modification, open for extension. Unknown names still fail loudly.

7. Which one when?

Simple Factory Factory Method Registry factory
Who decides One method, using a parameter A subclass, by overriding A lookup table
Mechanism if-else / switch Inheritance Map<String, Supplier<T>>
New product type Edit the factory Add a subclass Register it; nothing edited
Use when The choice depends on data A shared flow needs one varying object Types are added often, maybe by plug-ins

Common mistakes

Mistake Exact message / symptom Why Fix
if-else + new copied into many screens Delivered by Cycle / Quote: Rs 8/km (Bike) One decision, many copies One factory method decides
Vehicle v = new Vehicle(); error: Vehicle is abstract; cannot be instantiated Interfaces have no objects Ask a factory for a Vehicle
Two constructors Money(int rupees), Money(int paise) error: constructor Money(int) is already defined in class Money Same parameter types Money.ofRupees(), Money.fromPaise()
Integer.valueOf(128) == Integer.valueOf(128) false (127 gives true) Only -128..127 are guaranteed cached Compare with equals()
A concrete creator without the factory method error: HillDelivery is not abstract and does not override abstract method createVehicle() in DeliveryService The gap isn't filled Override createVehicle()
Factory returns null for unknown input later NullPointerException far away Silent failure Throw IllegalArgumentException with a clear message
Unknown name in the registry IllegalArgumentException: unknown vehicle: rocket Not registered Register it, or validate input

Mini project: a payment factory you never edit

Priya's chai app takes UPI and card payments. Build a registry-based Payments.of(name) factory, then add cash on delivery without editing Payments. Unknown methods must list the valid choices.

Solution
import java.util.*;
import java.util.function.Supplier;

interface Payment { String pay(int rupees); }
class Upi implements Payment { public String pay(int r) { return "UPI: Rs " + r + " sent to chaiwala@upi"; } }
class Card implements Payment { public String pay(int r) { return "Card: Rs " + r + " charged"; } }
class Cash implements Payment { public String pay(int r) { return "Cash: collect Rs " + r + " at the door"; } }

class Payments {
    private static final Map<String, Supplier<Payment>> makers = new LinkedHashMap<>();
    static { register("upi", Upi::new); register("card", Card::new); }
    static void register(String name, Supplier<Payment> maker) { makers.put(name, maker); }
    static Payment of(String name) {
        Supplier<Payment> m = makers.get(name);
        if (m == null) throw new IllegalArgumentException("unknown payment: " + name + ", try " + makers.keySet());
        return m.get();
    }
}
public class Main {
    public static void main(String[] args) {
        Payments.register("cash", Cash::new);            // added without editing Payments
        for (String p : List.of("upi", "card", "cash")) System.out.println(Payments.of(p).pay(120));
        try { Payments.of("cheque"); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
    }
}
UPI: Rs 120 sent to chaiwala@upi
Card: Rs 120 charged
Cash: collect Rs 120 at the door
unknown payment: cheque, try [upi, card, cash]

LinkedHashMap keeps insertion order, so the error lists the choices in a stable order. The static { ... } block is a static initializer: it runs once when the class is initialized.

Practice

1. Write Temperature.ofCelsius(double) and Temperature.fromFahrenheit(double) with a private constructor.

Answer
final class Temperature {
    private final double celsius;
    private Temperature(double c) { this.celsius = c; }
    static Temperature ofCelsius(double c) { return new Temperature(c); }
    static Temperature fromFahrenheit(double f) { return new Temperature((f - 32) * 5 / 9); }
    public String toString() { return String.format("%.1f C", celsius); }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(Temperature.ofCelsius(37));
        System.out.println(Temperature.fromFahrenheit(98.6));
    }
}
37.0 C
37.0 C

2. Add an EV scooter for parcels up to 5 kg to VehicleFactory.forWeight. Where exactly does the new line go, and why does order matter?

Answer

Between the cycle and bike checks: if (kg <= 5) return new EvScooter(); after kg <= 2 and before kg <= 10. The checks run top to bottom and the first match wins, so a wider range placed earlier would hide the narrower ones.

3. Is List.of(1, 2, 3) a Simple Factory, a static factory method, or the Factory Method pattern?

Answer

A static factory method (named of). It is not the Factory Method pattern, which needs a creator class whose subclasses override the factory method.

4. Add a RiverDelivery that uses a Boat to the Factory Method example. Which existing classes change?

Answer

None. Add class Boat implements Vehicle { public int perKm() { return 15; } } and class RiverDelivery extends DeliveryService { Vehicle createVehicle() { return new Boat(); } }.

5. What does Integer.valueOf(-128) == Integer.valueOf(-128) print, and should you rely on it?

Answer

true, because -128 is inside the guaranteed cache range. But don't rely on == for values: use equals().

Quick quiz

abstract class Shop {
    abstract String makeTea();
    String serve() { return "Serving " + makeTea(); }
}
class Mumbai extends Shop {
    String makeTea() { return "cutting chai"; }
}
// in main:
Shop s = new Mumbai();
System.out.println(s.serve());
  • A. Serving null
  • B. Serving cutting chai
  • C. Compile error: Shop is abstract
  • D. Serving makeTea()
Answer

B. serve() is written once in the creator and calls the factory method; the subclass Mumbai decides what gets made. new Mumbai() is fine; only new Shop() would fail.

Interview questions

  1. What is a factory? An object or method whose job is to create other objects, so callers don't depend on concrete classes.
  2. Simple Factory vs Factory Method? Simple Factory: one method decides from a parameter (not a GoF pattern). Factory Method: an abstract creator declares a creation method; subclasses override it to decide the product (GoF).
  3. What are the roles in Factory Method? Product, concrete product, creator, concrete creator.
  4. Why use static factory methods instead of constructors? Names, can reuse instances (caching, singletons), can return subtypes, the returned class can vary with the arguments.
  5. Why is Integer.valueOf(127) == Integer.valueOf(127) true but 128 false? valueOf caches -128..127 and returns the same object; outside that range it creates new objects.
  6. How do factories relate to the open-closed principle? A registry-based factory (or new subclasses in Factory Method) lets you add product types without modifying existing code.
  7. What should a factory do with unknown input? Throw a clear exception (e.g. IllegalArgumentException) rather than return null.
  8. Give JDK examples of factory methods. List.of, LocalDate.of, Integer.valueOf, Optional.of, Files.newBufferedReader, Calendar.getInstance.
  9. Downside of static factory methods? Classes with only private constructors can't be subclassed, and factory methods are harder to spot in docs than constructors (hence naming conventions).

Glossary

Term Meaning, with an example
Factory An object or method whose job is to create other objects. VehicleFactory
Product The type of object a factory creates. Vehicle
Concrete product A real class implementing the product. Bike, Jeep
Concrete class A class you can call new on (not an interface or abstract class). Bike
Simple Factory One class/method that holds the creation decision. VehicleFactory.forWeight(kg)
Parameterized factory A factory where a parameter selects the product. forWeight(6) gives a Bike
Static factory method A static method that creates and returns an object. Money.ofRupees(250)
of / from / valueOf Conventional names: build from parts / convert one value / longer form. List.of, Date.from, String.valueOf
getInstance / newInstance Maybe-the-same object / always a new object
Integer cache Integer.valueOf always reuses objects for -128..127
Reference equality (==) "Same object?" For values use equals()
Factory Method pattern GoF: an interface for creating an object, subclasses decide which class
Factory method The overridable creation method. createVehicle()
Creator The class that declares and uses the factory method. DeliveryService
Concrete creator A subclass that overrides the factory method. HillDelivery
Abstract class A class with gaps (abstract methods) that can't be instantiated
Abstract method A method with no body that subclasses must override. abstract Vehicle createVehicle();
Override A subclass replacing an inherited method (episode 8)
Default method An interface method with a body. default String name()
Registry A lookup table from names to makers. Map<String, Supplier<Vehicle>>
Registry-based factory A factory that creates by looking up a registered maker
Supplier<T> A function that takes nothing and returns a T (episode 5)
Method reference Short lambda naming an existing method or constructor. Bike::new
Open-closed principle Open for extension, closed for modification (episode 13)
IllegalArgumentException Standard unchecked exception for a bad argument. no vehicle for 900 kg
Static initializer A static { ... } block that runs once when the class is initialized

Summary

  • Copying if-else + new into many places makes creation decisions drift apart.
  • A Simple Factory puts the decision in one place; a parameterized factory picks the product from a parameter.
  • Static factory methods give creation a name (of, from, valueOf, getInstance, newInstance), can reuse objects (the Integer cache) and can return subtypes.
  • Factory Method (GoF): the creator holds the shared flow and an abstract factory method; concrete creators override it to choose the concrete product.
  • A registry-based factory adds new types without editing the factory: the open-closed principle.

Next episode: The Abstract Factory pattern.