What It Is
The Template Method pattern fixes the skeleton of an algorithm — the steps and their order — while letting the individual steps vary. The recipe is written once; each variant fills in its own steps.
Classically the skeleton lives in a base class. Go does it with a function that takes an interface: the function is the fixed recipe, the interface holds the variable steps.
Example: One Recipe, Two Drinks
MakeDrink owns the order: boil, brew, pour, extras. Tea and coffee only answer how to brew and what to add — they cannot reorder or skip steps.
The skeleton stays fixed
Both drinks follow the same four steps in the same order, because the order lives in one function. A new drink implements two methods and inherits the whole discipline.
Output: Go program and captured output
package main
import "fmt"
// The variable steps live in an interface...
type Steps interface {
Brew() string
Extras() string
}
// ...the fixed skeleton lives in one function.
func MakeDrink(name string, s Steps) {
fmt.Println("--", name)
fmt.Println("boil water")
fmt.Println(s.Brew())
fmt.Println("pour into cup")
fmt.Println(s.Extras())
}
type Tea struct{}
func (Tea) Brew() string { return "steep the tea leaves" }
func (Tea) Extras() string { return "add lemon" }
type Coffee struct{}
func (Coffee) Brew() string { return "run water through the coffee" }
func (Coffee) Extras() string { return "add milk" }
func main() {
MakeDrink("tea", Tea{})
MakeDrink("coffee", Coffee{})
}
When to Use It
Use it when several procedures share the same fixed sequence with different details — report generation, import pipelines, test setups.
Skip it when the variants also need different orders — forcing them under one skeleton bends the pattern until it breaks. And with one variant, the skeleton is just a function.
Pros and Cons
Pros: the sequence is enforced in one place; variants cannot forget or shuffle steps; shared steps are written once.
Cons: rigid by design — a variant that needs "almost the same, but..." fights the skeleton; too many hook methods make the recipe hard to follow.