☰ All patterns
Factory
Ask for what you want; let a function decide how to build it.
01
Explain it like I'm new
Real-life analogy
Ordering at a restaurant
You say 'one pasta, please'. You don't walk into the kitchen and cook it yourself. The kitchen (factory) knows which chef, pan and recipe to use and hands you a finished plate.
😩 The problem
Your code needs a Notifier, but which one (email, SMS, Slack) depends on config at runtime. Scattering if kind == "email" checks everywhere makes adding a new type painful.
💡 The pattern
Write one constructor function, NewNotifier(kind), that returns an interface. Callers depend on the interface only. Adding a new type means touching one switch.
02
Walk through the code
Click a step to highlight its lines. This is a complete program you can copy and run.
Press ▶ Run to execute this program.This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.
03
When should I use it?
✅ Reach for it when…
- •The concrete type is chosen at runtime (config, user input, flags).
- •You want callers to depend on an interface, not a struct.
🚫 Skip it when…
- •There's only ever one implementation. A plain NewThing() constructor is enough.
🐹 Go tip
In Go, 'factory' usually just means a NewXxx function. Return concrete types by default, and return an interface only when callers genuinely need to swap implementations.
🌍 You've already seen it in
sql.Open(driverName, dsn) and image.Decode both pick an implementation by name or format.
04
Quick check
One question. No pressure.
What does a Go factory function usually return when the caller shouldn't care about the concrete type?