Patterns for creating objects · Chapter 8

Factory pattern

Put object creation in one place. Simple factory, Factory Method and Abstract Factory told apart clearly, with full Java and Python code and the traps of each.

IntermediateInterview priority: High55 min
On this page
  1. The problem: the same new in every screen
  2. The idea: one place that knows how to make things
  3. Build it: the simple factory
  4. Factory Method: let subclasses decide
  5. Abstract Factory: a whole matching family
  6. The three side by side
  7. Lightweight and modern forms
  8. Where this breaks
  9. When not to use it
  10. Real uses in libraries and frameworks
  11. In the interview
  12. Quiz

The problem: the same new in every screen

A pizza shop has three ways to order: the website, the phone line and a menu app. Each one turns the customer's choice into an object:

// OrderScreen.java, PhoneOrders.java and MenuApp.java all contain this
Pizza p;
if (type.equals("marg"))      p = new Margherita();
else if (type.equals("veg"))  p = new Veggie();
else if (type.equals("pep"))  p = new Pepperoni();
else throw new IllegalArgumentException(type);

Three copies of the same branch means three places to edit when the menu changes, and three chances to forget one. When the phone line gets the new pizza and the menu app doesn't, customers see "unknown pizza". Worse, every screen now depends on every concrete pizza class, so a change to how a Veggie is built (a supplier lookup, a gluten-free base) ripples into code that only wanted "a pizza".

Every screen knows every pizza class

  1. Creating objects sounds easy: just write new. But when the right class depends on a choice, like which pizza a customer picked, the same if/else for new ends up copied into every screen of the app.

The underlying issue: deciding which class to create, and how, is mixed into code that should only use the result.

The idea: one place that knows how to make things

A factory is code whose job is to create objects. Callers say what they want ("veg") and get back something typed as the interface (Pizza). They never write new Veggie() and never import Veggie.

Callers ask the factory and get back "a Pizza"

  1. A factory is an object whose one job is making other objects. Callers ask PizzaFactory.create("veg") and get back “a Pizza”. They never write new for a specific pizza class.
  2. Inside, the factory holds the creation logic in one place. If a pizza needs special setup, like a gluten-free base or a supplier lookup, that lives here too.

"Factory" covers three related designs, and interviewers expect you to tell them apart:

NameIn one lineMechanism
Simple factoryOne method picks a class from a parameterA (usually static) method with a switch or a map
Factory Method (GoF)A base class calls an abstract "create" method that each subclass overridesInheritance
Abstract Factory (GoF)An object with several create methods that make a matching familyComposition: you pass the factory in

"GoF" means the 1994 Design Patterns book by the "Gang of Four". The simple factory is not one of their patterns; it is a common idiom, and the one you will write most often.

The roles, using the simple factory:

RoleIn this exampleResponsibility
Product (interface)PizzaWhat callers depend on
Concrete productsMargherita, Veggie, PepperoniThe real classes, hidden from callers
FactoryPizzaFactory.create(type)Turns a request into the right concrete product
ClientThe three ordering screensAsks for a product; uses only the interface

Build it: the simple factory

// The product interface: all that callers ever see
public interface Pizza {
    String name();
    int bakeMinutes();
}

// Concrete products
public final class Margherita implements Pizza {
    public String name() { return "Margherita"; }
    public int bakeMinutes() { return 10; }
}

public final class Veggie implements Pizza {
    private final boolean glutenFree;
    public Veggie(boolean glutenFree) { this.glutenFree = glutenFree; }
    public String name() { return glutenFree ? "Veggie (gluten-free)" : "Veggie"; }
    public int bakeMinutes() { return glutenFree ? 14 : 12; }
}

public final class Pepperoni implements Pizza {
    public String name() { return "Pepperoni"; }
    public int bakeMinutes() { return 11; }
}

// The factory: the only class that names the concrete pizzas
public final class PizzaFactory {
    private PizzaFactory() { }

    public static Pizza create(String type) {
        return switch (type) {
            case "marg"    -> new Margherita();
            case "veg"     -> new Veggie(false);
            case "veg-gf"  -> new Veggie(true);    // setup details live here, not in screens
            case "pep"     -> new Pepperoni();
            default -> throw new IllegalArgumentException("Unknown pizza: " + type);
        };
    }
}

// Client: each of the three screens is now one line
Pizza pizza = PizzaFactory.create(request.type());
oven.bake(pizza.name(), pizza.bakeMinutes());

Adding a pizza

One new class and one new line; the screens are untouched

  1. Now add a Hawaiian pizza. You write the new class and add one line to the factory. The three screens that order pizzas don’t change at all, because they only ever depended on the Pizza interface.

A Hawaiian pizza is one new class plus one line in the factory. Strictly, the factory itself is still edited, so it is not perfectly open/closed; but the edit is in one place, and the code that uses pizzas is closed to the change. If even that one line bothers you, let products register themselves in a map (see "Where this breaks" for the catch).

Factory Method: let subclasses decide

Now the shop opens branches. Every branch takes an order the same way (make the pizza, bake it, box it), but a New York branch makes thin crust and a Chicago branch makes deep dish. The ordering steps belong in one base class; only which pizza gets made differs.

The Factory Method pattern puts an abstract creation method in the base class and lets each subclass override it. The base class calls it in the middle of its own logic, without knowing which class comes back.

public final class ThinCrustPizza implements Pizza {
    private final String topping;
    public ThinCrustPizza(String topping) { this.topping = topping; }
    public String name() { return "Thin-crust " + topping; }
    public int bakeMinutes() { return 8; }
}

public final class DeepDishPizza implements Pizza {
    private final String topping;
    public DeepDishPizza(String topping) { this.topping = topping; }
    public String name() { return "Deep-dish " + topping; }
    public int bakeMinutes() { return 25; }
}

// The creator: fixed ordering steps, one step left open
public abstract class PizzaStore {
    public final Pizza order(String topping) {
        Pizza pizza = makePizza(topping);                 // the factory method
        System.out.printf("Baking %s for %d min%n", pizza.name(), pizza.bakeMinutes());
        System.out.println("Boxing " + pizza.name());
        return pizza;
    }

    protected abstract Pizza makePizza(String topping);  // subclasses decide
}

public final class NYStore extends PizzaStore {
    @Override protected Pizza makePizza(String topping) { return new ThinCrustPizza(topping); }
}

public final class ChicagoStore extends PizzaStore {
    @Override protected Pizza makePizza(String topping) { return new DeepDishPizza(topping); }
}

// Client
PizzaStore store = new ChicagoStore();
store.order("pepperoni");     // Baking Deep-dish pepperoni for 25 min

The tell-tale sign of Factory Method: the class that creates the product is also the class that uses it, and creation is one overridable step inside a bigger algorithm. That makes it a special case of Template Method, applied to creation.

Abstract Factory: a whole matching family

An app supports a dark and a light theme. A screen needs a button and a checkbox, and they must match: a dark button next to a light checkbox is a bug. If each widget is created separately, nothing stops that mix.

An Abstract Factory is an interface with one creation method per product in the family. Each implementation makes the whole family in one style. The client receives one factory object and gets every widget from it, so the pieces always match.

Factory Method (left) and Abstract Factory (right)

  1. You’ll meet two bigger cousins. Factory method: a base class leaves “which object to make” to its subclasses, like a NY store making thin crust. Abstract factory: one factory makes a whole matching family, like dark-theme buttons, menus and checkboxes that all fit together.
// The product family
public interface Button   { String render(); }
public interface Checkbox { String render(boolean checked); }

// The abstract factory: one method per product
public interface ThemeFactory {
    Button button(String label);
    Checkbox checkbox(String label);
}

// One concrete factory per family
record DarkButton(String label) implements Button {
    public String render() { return "[dark button: " + label + "]"; }
}
record DarkCheckbox(String label) implements Checkbox {
    public String render(boolean on) { return "[dark " + (on ? "x" : " ") + "] " + label; }
}
public final class DarkTheme implements ThemeFactory {
    public Button button(String label)     { return new DarkButton(label); }
    public Checkbox checkbox(String label) { return new DarkCheckbox(label); }
}

record LightButton(String label) implements Button {
    public String render() { return "(light button: " + label + ")"; }
}
record LightCheckbox(String label) implements Checkbox {
    public String render(boolean on) { return "(light " + (on ? "x" : " ") + ") " + label; }
}
public final class LightTheme implements ThemeFactory {
    public Button button(String label)     { return new LightButton(label); }
    public Checkbox checkbox(String label) { return new LightCheckbox(label); }
}

// Client: knows only the interfaces, so it cannot mix themes
public final class SettingsPage {
    private final ThemeFactory theme;
    public SettingsPage(ThemeFactory theme) { this.theme = theme; }

    public String render() {
        return theme.checkbox("Notifications").render(true) + "  " + theme.button("Save").render();
    }
}

// The choice is made once, at startup
ThemeFactory theme = user.prefersDark() ? new DarkTheme() : new LightTheme();
System.out.println(new SettingsPage(theme).render());

Notice the client gets its factory through the constructor. Abstract Factory is almost always combined with dependency injection: the program picks the family once (at startup, from config) and everything downstream stays consistent.

The three side by side

Simple factoryFactory MethodAbstract Factory
What variesWhich class, chosen by a parameterWhich class, chosen by the subclass you useWhich family of classes
How many productsOne kind (pizzas)One kind per creatorSeveral related kinds (button, checkbox, …)
MechanismA method with a switch or mapInheritance: override a create stepComposition: pass a factory object in
Who uses the productThe callerThe base class itself, in its own algorithmThe caller, via the factory it was given
Adding a new variantOne new class, one new lineOne new subclassOne new factory class plus its products
Adding a new product kindn/an/aPainful: every factory must change
ExamplePizzaFactory.create("veg")PizzaStore.makePizza()ThemeFactory.button() + .checkbox()

Two more look-alikes:

  • Static factory method (from Effective Java): a named static method used instead of a constructor, such as List.of(…), Integer.valueOf(5) or LocalDate.of(2026, 11, 18). It can have a meaningful name, return a cached instance, or return a hidden subclass. Despite the name, it is not the GoF Factory Method, which is an overridable instance method. Python's equivalent is an alternative constructor written as a @classmethod, like datetime.fromtimestamp(ts).
  • Builder: also about creation, but for one complex object assembled step by step. A factory decides which class to make in one call; a builder decides how to assemble one object over many calls.

Lightweight and modern forms

You rarely need a factory class hierarchy. Most of the time a map from key to constructor is the whole factory:

public final class PizzaFactory {
    private static final Map<String, Supplier<Pizza>> MENU = Map.of(
        "marg",   Margherita::new,
        "veg",    () -> new Veggie(false),
        "veg-gf", () -> new Veggie(true),
        "pep",    Pepperoni::new
    );

    public static Pizza create(String type) {
        Supplier<Pizza> maker = MENU.get(type);
        if (maker == null) throw new IllegalArgumentException("Unknown pizza: " + type);
        return maker.get();
    }
}

// A factory can also be a parameter: whoever calls decides what gets made
public final class Oven {
    public List<Pizza> batch(Supplier<? extends Pizza> maker, int count) {
        List<Pizza> out = new ArrayList<>();
        for (int i = 0; i < count; i++) out.add(maker.get());
        return out;
    }
}
new Oven().batch(Margherita::new, 6);

In larger apps, a dependency-injection container (Spring, Guice, FastAPI's Depends) is a general-purpose factory: you declare how to build each type once (a Spring @Bean method is literally a factory method) and the container builds and wires everything.

Where this breaks

When not to use it

Real uses in libraries and frameworks

  • Factory Method: Collection.iterator(). Each collection overrides it to return its own iterator, and code like the enhanced for loop uses the result without knowing the class. JDBC's Connection.createStatement() works the same way.
  • Simple / static factories: Calendar.getInstance(), NumberFormat.getCurrencyInstance(locale), List.of(…), Executors.newFixedThreadPool(4).
  • Abstract Factory: javax.xml.parsers.DocumentBuilderFactory.newInstance() returns a factory for the installed XML parser, which then creates parsers of that implementation.
  • Python: logging.getLogger(name), collections.defaultdict(factory), @classmethod alternative constructors like dict.fromkeys(…) and datetime.fromisoformat(…).
  • Frameworks: Spring's @Bean methods and FactoryBean; Django's get_user_model().

In the interview

Your turn: notifications

A system sends alerts by email, SMS and push notification. The channel comes from each user's preferences. SMS needs an API key and a sender number; email needs an SMTP host; push needs a device token per user. Sketch the interface, the factory, and the line of code where an alert is sent.

Compare with our answer
public interface Notifier { void send(String userId, String message); }

public final class EmailNotifier implements Notifier {
    private final String smtpHost;
    public EmailNotifier(String smtpHost) { this.smtpHost = smtpHost; }
    public void send(String userId, String message) { /* look up address, send via smtpHost */ }
}
public final class SmsNotifier implements Notifier {
    private final String apiKey, from;
    public SmsNotifier(String apiKey, String from) { this.apiKey = apiKey; this.from = from; }
    public void send(String userId, String message) { /* look up phone, call SMS API */ }
}
public final class PushNotifier implements Notifier {
    private final DeviceTokens tokens;
    public PushNotifier(DeviceTokens tokens) { this.tokens = tokens; }
    public void send(String userId, String message) { /* tokens.forUser(userId) → push */ }
}

public enum Channel { EMAIL, SMS, PUSH }

public final class NotifierFactory {
    private final Map<Channel, Notifier> byChannel;
    public NotifierFactory(Config cfg, DeviceTokens tokens) {
        byChannel = Map.of(
            Channel.EMAIL, new EmailNotifier(cfg.smtpHost()),
            Channel.SMS,   new SmsNotifier(cfg.smsKey(), cfg.smsFrom()),
            Channel.PUSH,  new PushNotifier(tokens));
    }
    public Notifier forChannel(Channel c) { return byChannel.get(c); }
}

// sending
factory.forChannel(user.preferredChannel()).send(user.id(), "Your order has shipped");

Each notifier's configuration goes in its own constructor, so the shared interface stays small. Notifiers here are stateless and reusable, so the factory builds each once and hands out the same one; if they held per-request state it would create a new one per call.

A strong answer mentions: one Notifier interface with one method · per-channel configuration in each constructor, not in the interface · an enum rather than raw strings for the channel · creation in one factory (built from config at startup) · whether instances are shared or created per call · a fallback when a channel fails or is missing.

Your turn: the requirement changes

The shop expands to the EU. An order now needs a PaymentGateway, a TaxCalculator and an InvoiceFormatter, and they must match the region: a US order must never be taxed with EU VAT rules or invoiced in the EU format. Later, legal will add a fourth piece, a ConsentChecker. Which factory variant fits, and what does the fourth piece cost you?

Compare with our answer
  • Three related products that must match: an Abstract Factory, RegionFactory, with payments(), tax() and invoices(), implemented by UsRegion and EuRegion.
  • The order service receives one RegionFactory (chosen from the order's country) and gets all three from it, so it cannot mix regions.
  • Adding a region (UK) is one new factory class plus its products, and no existing code changes.
  • Adding a product (ConsentChecker) changes the interface and every region factory. Soften it with a default method that throws or returns a no-op until each region implements it, and test that every region provides every piece.

A strong answer mentions: Abstract Factory, because the products must stay consistent · one factory chosen once per order or per deployment · new family = cheap, new product kind = touches all factories · a default method or a test as mitigation · not choosing three separate simple factories, which would allow mixing.

Factory on one page
  • Intent: keep "which class, and how to build it" in one place; callers depend on the interface only.
  • Simple factory: a method with a switch or a Map<String, Supplier<T>>. An idiom, not a GoF pattern; the one you'll use most.
  • Factory Method: abstract createX() in a base class, overridden by subclasses, called inside the base class's own algorithm (inheritance; cousin of Template Method).
  • Abstract Factory: an object with one create method per product in a family; pass it in, and all pieces match (composition).
  • Abstract Factory trade-off: new family is cheap; new product kind changes every factory.
  • Static factory method (List.of, Integer.valueOf) is a named constructor, not the GoF Factory Method.
  • Self-registration trap: Java static blocks and Python decorators run only when the class or module is loaded.
  • Smell: instanceof checks after creation; skip it for one class created in one place.
Interactive labPractise it: ship menu changes with and without a factoryOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. A UI toolkit must draw Windows-style and macOS-style widgets, and one window must never mix the two styles. Which design fits best?

2. ReportExporter.export() writes a header, the rows and a footer in a fixed order, and calls an abstract createWriter() that CsvExporter and PdfExporter override. Which pattern is this?

3. An abstract ThemeFactory has button() and checkbox(), with three themes. Designers add a slider. What has to change?

4. Each pizza class registers itself in the factory from a static { … } block. Tests pass, but production says "Unknown pizza: haw" even though Hawaiian is on the classpath. Why?

5. A reviewer says Integer.valueOf(5) is an example of the GoF Factory Method pattern. What is the best response?

6. After adding PizzaFactory, the kitchen code still says if (pizza instanceof Veggie) oven.setTemp(200). What is the best change?

7. Which situation is the weakest case for introducing a factory?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.