The Problem It Solves
// scattered across 12 call sites:
if (type.equals("push")) n = new PushNotification(channels);
else if (type.equals("sms")) n = new SmsNotification(provider);
else if (type.equals("email")) n = new EmailNotification(smtp);
Creation logic duplicated everywhere means: adding a channel edits twelve files, and every call site must know every concrete class plus its constructor dependencies. Simple factory is the smallest fix — one static method owns creation; callers ask for types, not classes.
Mechanics
class NotificationFactory {
static Notification create(String type) {
return switch (type) {
case "push" -> new PushNotification(pushChannels);
case "sms" -> new SmsNotification(smsProvider);
case "email" -> new EmailNotification(smtp);
default -> throw new IllegalArgumentException(type);
};
}
}
// all 12 sites become:
Notification n = NotificationFactory.create("push");
Constructor wiring (channels, providers, credentials) now lives in exactly one place. Callers depend on the Notification interface only — program-to-interface applied at the creation seam.
What It Is and Is Not
| Verdict | |
|---|---|
| A GoF pattern? | No — an idiom; GoF’s creational patterns solve harder variants |
| Sufficient when variants are known and closed? | Yes — usually the right stop |
| Enough when new variants arrive from outside code (plugins, config)? | No — see Factory Method |
| Testable? | Yes — inject the factory, or make it an interface with one impl |
Trade-offs
Direct new | Simple factory | |
|---|---|---|
| Wiring knowledge spread | Every call site | One place |
| Adding a variant | Edit N sites | Edit one switch |
| New variant without recompiling callers | Impossible | Still impossible (that needs registry/Factory Method) |
| Indirection cost | None | One hop |
When to Graduate
- Variants chosen by external configuration at runtime → replace switch with a
Map<String, Supplier<Notification>>registry — still a simple factory shape. - Different families of related products → Abstract Factory territory.
- Subclasses should decide which product they create (framework style) → Factory Method.
Interview Framing
- Naming it correctly matters: “simple factory idiom” shows taxonomy precision; calling it “the factory pattern” blurs three distinct things.
- Strong candidates mention the registry upgrade path unprompted — it is the production-grade evolution of this idiom.
Failure Modes
- Factory becoming a god-object knowing every constructor dependency in the system — split factories per product family.
- Passing raw strings where an enum would prevent typo-driven runtime failures.
Premium Content
Unlock Simple Factory and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans