Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Simple Factory
LLD

Simple Factory

Learn how to centralize object creation and hide construction logic behind a factory.

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 newSimple factory
Wiring knowledge spreadEvery call siteOne place
Adding a variantEdit N sitesEdit one switch
New variant without recompiling callersImpossibleStill impossible (that needs registry/Factory Method)
Indirection costNoneOne 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.

My Private Notes

Notes are auto-saved locally to this device.