Factory
Definition
Factory
- In plain English
- A factory is a function that creates values for you, hiding which concrete type or setup is used.
- Think of it like
- It is like ordering "a medium coffee" without needing to know which machine makes it.
Why it exists
Every scanner chooses day, weekend or VIP ticket types itself. Adding a ticket means finding every creation branch.
Move that decision into one function. Scanners can then use the returned interface.
How it works
Simple factory
- In plain English
- A simple factory is one function that picks which concrete type to create based on an input.
- Think of it like
- Like a ticket desk that hands out a different wristband depending on the ticket you bought.
You already met constructor functions. NewX is an ordinary function by convention; Go has no class-constructor syntax.
package tickets
import (
"errors"
"fmt"
)
type Ticket interface{ Days() int }
type DayTicket struct{}
func (DayTicket) Days() int { return 1 }
type WeekendTicket struct{}
func (WeekendTicket) Days() int { return 2 }
type VIPTicket struct{}
func (VIPTicket) Days() int { return 3 }
func NewTicket(kind string) (Ticket, error) {
switch kind {
case "day":
return DayTicket{}, nil
case "weekend":
return WeekendTicket{}, nil
case "vip":
return VIPTicket{}, nil
default:
return nil, errors.New("unknown ticket")
}
}
func Demo() {
t, err := NewTicket("weekend")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(t.Days())
}
DayTicket, WeekendTicket and VIPTicket satisfy Ticket; NewTicket creates a Ticket value.
Factory registry
- In plain English
- A factory registry is a map from names to creation functions, so new types can register themselves.
- Think of it like
- Like a phone directory listing who to call for each service.
- Constructor: NewX validates inputs and supplies defaults.
- Simple factory: one function chooses the concrete type.
- Registry: a map connects names to creation functions from other packages.
Examples
Reject closed-hour appointments
You create an appointment for a pet, vet and time. The clinic accepts appointments from 09:00 until 17:00.
package main
import (
"errors"
"fmt"
"time"
)
type Appointment struct {
pet, vet string
at time.Time
}
func NewAppointment(pet, vet string, at time.Time) (Appointment, error) {
if pet == "" || vet == "" {
return Appointment{}, errors.New("pet and vet required")
}
if at.Hour() < 9 || at.Hour() >= 17 {
return Appointment{}, errors.New("clinic closed")
}
return Appointment{pet, vet, at}, nil
}
func main() {
at := time.Date(2030, 1, 2, 18, 0, 0, 0, time.UTC)
_, err := NewAppointment("Milo", "Lee", at)
fmt.Println(err)
}
Check the error before using the appointment. Private fields hide its details, but Go still permits a zero Appointment. This example assumes at uses the clinic’s time zone.
The insight
A constructor factory guarantees a valid start.
Keep scanners independent
NewTicket("weekend") returns Ticket. Your scanner reads Days without naming the concrete ticket.
package tickets
import (
"errors"
"fmt"
)
type Ticket interface{ Days() int }
type DayTicket struct{}
func (DayTicket) Days() int { return 1 }
type WeekendTicket struct{}
func (WeekendTicket) Days() int { return 2 }
type VIPTicket struct{}
func (VIPTicket) Days() int { return 3 }
func NewTicket(kind string) (Ticket, error) {
switch kind {
case "day":
return DayTicket{}, nil
case "weekend":
return WeekendTicket{}, nil
case "vip":
return VIPTicket{}, nil
default:
return nil, errors.New("unknown ticket")
}
}
func Demo() {
t, err := NewTicket("weekend")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(t.Days())
}
The factory handles an unknown kind with an error. The scanner receives only a valid interface when creation succeeds.
The insight
Callers depend on the interface, not the type list.
Register a sensor model
Your configuration names model TX-200. A map chooses its driver creation function.
package tickets
import (
"errors"
"fmt"
)
type Sensor interface{ Celsius() float64 }
type TX200 struct{}
func (TX200) Celsius() float64 { return 21.5 }
var drivers = map[string]func() Sensor{
"TX-200": func() Sensor { return TX200{} },
}
func NewSensor(model string) (Sensor, error) {
makeSensor, ok := drivers[model]
if !ok {
return nil, errors.New("unknown model")
}
return makeSensor(), nil
}
func Demo() {
s, err := NewSensor("TX-200")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(s.Celsius())
}
Register all models before serving requests. This map stays unchanged afterward; concurrent registration would need protection.
The insight
A registry factory keeps creation open for new types.
Trade-offs
Pros
- Creation logic lives in one place.
- Callers use interfaces.
- Construction can validate inputs.
Cons
- Adds a layer.
- A large switch can become difficult to maintain.
Use when
- Several types share an interface.
- Creation needs validation or defaults.
Avoid when
- One struct literal reads well.
- Creation has no decisions or validation.
Quick check
Takeaways
- A factory hides how values are made.
- In Go, NewX functions are factories.
- Use a registry map when new types should plug in.