Patterns: creation · 3 MIN READ
Factory Method: supply the creation step
Vary product creation without duplicating the algorithm that uses it.
Vary product creation without duplicating the algorithm that uses it. The classic Factory Method lets an algorithm ask an overridable creation operation for a product. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.
Creational pattern · A MAP OF THE IDEA
- Caller supplies a creation hook
- Stable algorithm asks for a product
- Algorithm uses the product contract
Useful when
- An algorithm should vary product creation
- Tests need a predictable product implementation
Watch out
- Constructor injection may be simpler
- Creation must define errors and cleanup ownership
Implementation & operation cost: Low to medium
Fit depends on the task
Editorial suitability, not benchmarks or a universal ranking. Styles describe different axes and can be combined.
The design decision
The classic Factory Method lets an algorithm ask an overridable creation operation for a product. Go usually replaces the inheritance hook with a function or small interface. Preserve that separation: a switch returning objects by name is a simple factory, not the full classic structure.
A complete Go example
Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.
package main
import (
"bytes"
"fmt"
"io"
)
type Report struct{ NewWriter func() io.Writer }
func (r Report) Write() io.Writer {
w := r.NewWriter()
fmt.Fprint(w, "report")
return w
}
func main() {
r := Report{NewWriter: func() io.Writer { return &bytes.Buffer{} }}
w := r.Write()
fmt.Println(w.(*bytes.Buffer).String())
}
// Output:
// report
Report.Write owns the stable algorithm and calls the supplied creation hook. main chooses a buffer product without rewriting the report logic. The type assertion is used only to inspect this known test product, not as the algorithm’s dependency.
Tradeoffs and the simpler alternative
Use a plain constructor when the caller can create the dependency directly. Real writers can fail, so production report code should return write errors and define who closes the writer. A factory function should not hide expensive creation or ownership rules.
TAKE THIS WITH YOU
Varies creation through an algorithm’s supplied hook. Use a plain constructor when the caller can create the dependency directly. Real writers can fail, so production report code should return write errors and define who closes the writer. A factory function should not hide expensive creation or ownership rules.
Check your understanding
Which statement best describes Factory Method: supply the creation step?
Go to the source
Progress stays in this browser. No account needed.