What It Is
The Factory Method pattern puts the creation of an object behind a function. The caller says what it wants — the factory decides which concrete type to build and returns it as an interface.
The caller never touches the concrete types, so new kinds can be added without changing any calling code. In Go this is simply a NewSomething() function that returns an interface.
Example: A Storage Factory
NewStorage("disk") and NewStorage("memory") return different concrete types behind the same Storage interface — the caller cannot tell the difference, and does not need to.
The factory picks the type
The switch over kinds lives in one place — the factory. The rest of the program only knows the interface.
Output: Go program and captured output
package main
import "fmt"
type Storage interface {
Save(data string) string
}
type DiskStore struct{}
func (DiskStore) Save(d string) string { return "disk: saved " + d }
type MemoryStore struct{}
func (MemoryStore) Save(d string) string { return "memory: kept " + d }
// The factory decides which concrete type to build.
func NewStorage(kind string) Storage {
switch kind {
case "memory":
return MemoryStore{}
default:
return DiskStore{}
}
}
func main() {
for _, kind := range []string{"disk", "memory"} {
s := NewStorage(kind)
fmt.Println(s.Save("order #1042"))
}
}
When to Use It
Use it when the concrete type depends on something known only at run time — a config value, a user choice, an environment — or when you want creation logic in exactly one place.
Skip it when there is only one implementation and no sign of a second. store := DiskStore{} needs no factory.
Pros and Cons
Pros: creation logic in one place; callers depend only on the interface; adding a kind touches only the factory.
Cons: one more layer to read through; with a single implementation it is pure ceremony.