Template Method
Defines the skeleton of an algorithm, letting subclasses fill in specific steps.
Understanding Template Method
The Template Method pattern defines the skeleton of an algorithm in a base type, deferring some steps to subtypes or injected functions. The overall structure stays fixed while specific steps can vary. In Go, since there\'s no class inheritance, this is implemented using composition: the template struct holds function fields (or an interface) for the customizable steps, while the main method calls them in a fixed order. Go's first-class functions make this pattern particularly elegant — you can inject behavior via function fields or closures without needing separate struct types.
Key Concepts
- •Template method — the fixed algorithm skeleton that calls abstract steps in a defined order
- •Hook functions — customizable steps that subtypes or injected functions implement
- •Inversion of control — the template controls the flow — hooks only implement specific steps
- •Go idiom: function fields — in Go, use function-typed struct fields instead of abstract methods for flexibility
When to Use
- • Multiple variants of an algorithm share the same overall structure
- • You want to enforce a specific order of operations while allowing customization
- • You\'re building a framework where users plug in specific steps
- • Data processing pipelines with fixed stages but varying logic per stage
- • Each variant needs a completely different algorithm — Strategy is a better fit
- • The template becomes too rigid and most subclasses override every step
- • Simple function composition achieves the same result with less ceremony
Structure
How It Works
Template Method
Base class defines algorithm skeleton.
Basic Implementation
Data mining with ETL template:
Real-World Example: Game AI
Game AI with different strategies sharing common turn structure: