Golang — Strategy Pattern

Matthias Bruns
2 min readMar 27, 2023

The “Gang of Four” (GoF) patterns are a set of 23 design patterns that were defined by four authors in their book “Design Patterns: Elements of Reusable Object-Oriented Software”. The Strategy Pattern is one of the patterns defined in the book. In this article, we will discuss how to implement the Strategy Pattern in Golang.

What is the Strategy Pattern?

The Strategy Pattern is a behavioral design pattern that enables selecting an algorithm at runtime. This pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. The pattern lets the algorithm vary independently from the clients that use it.

Implement the Strategy Pattern

To implement the Strategy Pattern in Golang, we need to define an interface that declares the algorithm’s methods. We then implement the interface for each algorithm we want to use. Finally, we define a context struct that has a field of the interface type. This context struct executes the algorithm’s methods through the interface’s field.

Here’s an example of implementing the Strategy Pattern for sorting algorithms:

package main

import (
"fmt"
)

type Sorter interface {
Sort([]int) []int
}

type BubbleSort struct{}

func (bs *BubbleSort) Sort(arr []int) []int {
// Bubble…

--

--

Matthias Bruns

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