Golang — Template Method Pattern

Matthias Bruns
3 min readMar 29, 2023

The Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a superclass but lets subclasses override specific steps of the algorithm without changing its structure. In other words, the Template Method Pattern provides a template for performing an operation but allows the subclasses to modify certain steps of the operation without changing its overall structure.

The Template Method Pattern is a part of the “Gang of Four” design patterns, which were first introduced in their book “Design Patterns: Elements of Reusable Object-Oriented Software”. The “Gang of Four” includes Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. These patterns are widely used in software development to solve commonly occurring problems in object-oriented programming.

Example

Let’s consider a real-world example of how the Template Method Pattern can be used in Golang programming. Suppose we want to create a program that reads data from different sources and then processes it. The sources can be files, databases, or even remote APIs. We can create an abstract class that defines the template for reading and processing data.

type DataReaderProcessor interface {
ReadData() ([]byte, error)
ProcessData(data []byte) error
GetDataSourceName() string
}

type…

--

--

Matthias Bruns

Senior Freelancer & Technical Lead Working as a Golang developer since 2020. as a mobile developer since 2013. Focussed on architecture & testability.