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.
On this page
- The problem: the same new in every screen
- The idea: one place that knows how to make things
- Build it: the simple factory
- Factory Method: let subclasses decide
- Abstract Factory: a whole matching family
- The three side by side
- Lightweight and modern forms
- Where this breaks
- When not to use it
- Real uses in libraries and frameworks
- In the interview
- 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
- 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"
- 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.
- 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:
| Name | In one line | Mechanism |
|---|---|---|
| Simple factory | One method picks a class from a parameter | A (usually static) method with a switch or a map |
| Factory Method (GoF) | A base class calls an abstract "create" method that each subclass overrides | Inheritance |
| Abstract Factory (GoF) | An object with several create methods that make a matching family | Composition: 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:
| Role | In this example | Responsibility |
|---|---|---|
| Product (interface) | Pizza | What callers depend on |
| Concrete products | Margherita, Veggie, Pepperoni | The real classes, hidden from callers |
| Factory | PizzaFactory.create(type) | Turns a request into the right concrete product |
| Client | The three ordering screens | Asks 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());class Pizza:
"""The product interface: all that callers ever see."""
def name(self) -> str: raise NotImplementedError
def bake_minutes(self) -> int: raise NotImplementedError
class Margherita(Pizza):
def name(self): return "Margherita"
def bake_minutes(self): return 10
class Veggie(Pizza):
def __init__(self, gluten_free: bool = False):
self.gluten_free = gluten_free
def name(self): return "Veggie (gluten-free)" if self.gluten_free else "Veggie"
def bake_minutes(self): return 14 if self.gluten_free else 12
class Pepperoni(Pizza):
def name(self): return "Pepperoni"
def bake_minutes(self): return 11
# The factory. Classes are callables in Python, so a dict of them is enough.
_MENU = {
"marg": Margherita,
"veg": Veggie,
"veg-gf": lambda: Veggie(gluten_free=True),
"pep": Pepperoni,
}
def create_pizza(kind: str) -> Pizza:
try:
return _MENU[kind]()
except KeyError:
raise ValueError(f"Unknown pizza: {kind}") from None
# Client
pizza = create_pizza(request.kind)
oven.bake(pizza.name(), pizza.bake_minutes())Adding a pizza
One new class and one new line; the screens are untouched
- 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 minfrom abc import ABC, abstractmethod
class ThinCrustPizza(Pizza):
def __init__(self, topping): self.topping = topping
def name(self): return f"Thin-crust {self.topping}"
def bake_minutes(self): return 8
class DeepDishPizza(Pizza):
def __init__(self, topping): self.topping = topping
def name(self): return f"Deep-dish {self.topping}"
def bake_minutes(self): return 25
class PizzaStore(ABC):
def order(self, topping: str) -> Pizza:
pizza = self.make_pizza(topping) # the factory method
print(f"Baking {pizza.name()} for {pizza.bake_minutes()} min")
print(f"Boxing {pizza.name()}")
return pizza
@abstractmethod
def make_pizza(self, topping: str) -> Pizza: ... # subclasses decide
class NYStore(PizzaStore):
def make_pizza(self, topping): return ThinCrustPizza(topping)
class ChicagoStore(PizzaStore):
def make_pizza(self, topping): return DeepDishPizza(topping)
# Client
store = ChicagoStore()
store.order("pepperoni") # Baking Deep-dish pepperoni for 25 minThe 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)
- 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());from abc import ABC, abstractmethod
from dataclasses import dataclass
# The product family
@dataclass
class DarkButton:
label: str
def render(self): return f"[dark button: {self.label}]"
@dataclass
class DarkCheckbox:
label: str
def render(self, on: bool): return f"[dark {'x' if on else ' '}] {self.label}"
@dataclass
class LightButton:
label: str
def render(self): return f"(light button: {self.label})"
@dataclass
class LightCheckbox:
label: str
def render(self, on: bool): return f"(light {'x' if on else ' '}) {self.label}"
# The abstract factory
class ThemeFactory(ABC):
@abstractmethod
def button(self, label: str): ...
@abstractmethod
def checkbox(self, label: str): ...
class DarkTheme(ThemeFactory):
def button(self, label): return DarkButton(label)
def checkbox(self, label): return DarkCheckbox(label)
class LightTheme(ThemeFactory):
def button(self, label): return LightButton(label)
def checkbox(self, label): return LightCheckbox(label)
# Client
class SettingsPage:
def __init__(self, theme: ThemeFactory):
self.theme = theme
def render(self) -> str:
return f"{self.theme.checkbox('Notifications').render(True)} {self.theme.button('Save').render()}"
theme = DarkTheme() if user.prefers_dark else LightTheme()
print(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 factory | Factory Method | Abstract Factory | |
|---|---|---|---|
| What varies | Which class, chosen by a parameter | Which class, chosen by the subclass you use | Which family of classes |
| How many products | One kind (pizzas) | One kind per creator | Several related kinds (button, checkbox, …) |
| Mechanism | A method with a switch or map | Inheritance: override a create step | Composition: pass a factory object in |
| Who uses the product | The caller | The base class itself, in its own algorithm | The caller, via the factory it was given |
| Adding a new variant | One new class, one new line | One new subclass | One new factory class plus its products |
| Adding a new product kind | n/a | n/a | Painful: every factory must change |
| Example | PizzaFactory.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)orLocalDate.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, likedatetime.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);from collections import defaultdict
from typing import Callable
# A class is already a factory: calling it makes an instance
def batch(maker: Callable[[], Pizza], count: int) -> list[Pizza]:
return [maker() for _ in range(count)]
batch(Margherita, 6)
# The standard library takes factories as arguments too
orders_by_table = defaultdict(list) # list is the factory for missing keysIn 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 enhancedforloop uses the result without knowing the class. JDBC'sConnection.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),@classmethodalternative constructors likedict.fromkeys(…)anddatetime.fromisoformat(…). - Frameworks: Spring's
@Beanmethods andFactoryBean; Django'sget_user_model().
In the interview
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");from enum import Enum
class Notifier:
def send(self, user_id: str, message: str) -> None: raise NotImplementedError
class EmailNotifier(Notifier):
def __init__(self, smtp_host): self.smtp_host = smtp_host
def send(self, user_id, message): ... # look up address, send via SMTP
class SmsNotifier(Notifier):
def __init__(self, api_key, sender): self.api_key, self.sender = api_key, sender
def send(self, user_id, message): ... # look up phone, call SMS API
class PushNotifier(Notifier):
def __init__(self, tokens): self.tokens = tokens
def send(self, user_id, message): ... # tokens.for_user(user_id) -> push
class Channel(Enum):
EMAIL = "email"
SMS = "sms"
PUSH = "push"
class NotifierFactory:
def __init__(self, cfg, tokens):
self._by_channel = {
Channel.EMAIL: EmailNotifier(cfg.smtp_host),
Channel.SMS: SmsNotifier(cfg.sms_key, cfg.sms_from),
Channel.PUSH: PushNotifier(tokens),
}
def for_channel(self, c: Channel) -> Notifier:
return self._by_channel[c]
factory.for_channel(user.preferred_channel).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.
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, withpayments(),tax()andinvoices(), implemented byUsRegionandEuRegion. - 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.
- 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:
instanceofchecks after creation; skip it for one class created in one place.
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?
The widgets form a family that must stay consistent, which is exactly Abstract Factory: a window receives one factory and every widget it creates matches. A single simple factory can still be called with mixed styles.
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?
Creation is one overridable step inside the base class's own algorithm: the definition of Factory Method. Abstract Factory is a separate object, passed in, that makes several related products.
3. An abstract ThemeFactory has button() and checkbox(), with three themes. Designers add a slider. What has to change?
Abstract Factory makes a new family cheap but a new product kind expensive: the interface grows and every implementation must follow. A Java default method can soften it, but the work is still there.
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?
A static initialiser runs only when its class is initialised, which needs something to touch it. Tests touched it; production didn't. Use an explicit list, ServiceLoader or component scanning instead.
5. A reviewer says Integer.valueOf(5) is an example of the GoF Factory Method pattern. What is the best response?
GoF Factory Method is an instance method that subclasses override. valueOf is static, cannot be overridden, and exists to give creation a name and allow caching (it caches -128 to 127).
6. After adding PizzaFactory, the kitchen code still says if (pizza instanceof Veggie) oven.setTemp(200). What is the best change?
Checking concrete types after creation re-couples the kitchen to every pizza class and defeats the factory. Behaviour that varies by type belongs on the type, behind the interface.
7. Which situation is the weakest case for introducing a factory?
With one class and one creation site there is nothing to hide or centralise; new User(…) is clearer. The others vary by input or must stay consistent, which is what factories are for.
Score 60% or more and the lesson is marked complete.