Patterns: behavior · 3 MIN READ
Template Method: fixed workflow, supplied steps
Adapt the inheritance-based intent using composition in Go.
Adapt the inheritance-based intent using composition in Go. Template Method defines the order of an algorithm while allowing selected steps to vary. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.
Behavioral pattern · A MAP OF THE IDEA
- Fixed workflow starts the operation
- Supplied loading and formatting steps run
- Workflow owns ordering and finalization
Useful when
- Several workflows share a meaningful sequence
- Only selected steps should vary
Watch out
- Too many hooks obscure control flow
- Real I/O requires error and cleanup contracts
Implementation & operation cost: 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
Template Method defines the order of an algorithm while allowing selected steps to vary. Go does not override inherited methods, so explicit function dependencies can carry the same intent. The stable workflow should enforce the order and define what happens if a step fails.
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 (
"fmt"
"strings"
)
type Workflow struct {
Load func() string
Format func(string) string
}
func (w Workflow) Run() string {
raw := w.Load()
return "result: " + w.Format(raw)
}
func main() {
w := Workflow{Load: func() string { return "go" }, Format: strings.ToUpper}
fmt.Println(w.Run())
}
// Output:
// result: GO
Run fixes loading before formatting and owns the result prefix. Callers replace steps without changing this order. This is a composition-based Go adaptation of Template Method, rather than a claim that Go supports virtual method overrides.
Tradeoffs and the simpler alternative
If every step varies independently, a plain pipeline may be clearer than a framework with many hooks. Validate required callbacks at construction. Use error-returning steps and cleanup rules for real I/O, and avoid hooks that can silently skip mandatory security checks.
TAKE THIS WITH YOU
Fixes algorithm order while supplying selected steps. If every step varies independently, a plain pipeline may be clearer than a framework with many hooks. Validate required callbacks at construction. Use error-returning steps and cleanup rules for real I/O, and avoid hooks that can silently skip mandatory security checks.
Check your understanding
Which statement best describes Template Method: fixed workflow, supplied steps?
Go to the source
Progress stays in this browser. No account needed.