Golang — State Pattern

Matthias Bruns
3 min readMar 26, 2023

In this article, we will be exploring how the State Pattern can be applied to a game in Golang. We will use a simple game where the player can move in different directions and perform different actions based on their current state.

What is the State Pattern?

The State Pattern is a behavioral design pattern that allows an object to alter its behavior when its internal state changes. This pattern is useful when an object needs to change its behavior based on its current state, but you don’t want to use a long list of conditional statements to handle all the possible states.

How does it work?

The State Pattern works by defining a separate class for each possible state of an object. Each of these classes implements a common interface that defines the methods for the object’s behavior. The object itself holds a reference to the current state class, and delegates all method calls to that class. When the object’s state changes, it simply updates the reference to the appropriate state class.

An example

Let’s say we have a simple game where the player can move in different directions and perform different actions based on their current state. The player can be in three possible states: “Idle”, “Walking”, and “Jumping”. Here’s how we could implement…

--

--

Matthias Bruns

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