Golang — Visitor Pattern

Matthias Bruns
3 min readMar 30, 2023

The Gang of Four design patterns are widely used in software development. One of the most useful ones is the Visitor Pattern. In this article, we will discuss the Visitor Pattern in the context of Golang.

What is the Visitor Pattern?

The Visitor Pattern is a behavioral design pattern that allows us to separate an algorithm from an object structure on which it operates. It is useful when we have a complex object structure and we want to perform some operations on it without changing the classes of the objects in the structure.

How does it work?

The Visitor Pattern works by separating the algorithm from the object structure. To achieve this, we define an interface that represents the algorithm. This interface will have a method for each class in the object structure. Each method will take an instance of the class as an argument. The object structure will also have an interface that defines a method for accepting the visitor. This method will take an instance of the visitor interface as an argument. When the accept method is called, the visitor’s corresponding method for the class will be called.

Example

Suppose we have a complex object structure that represents a company’s employees. The structure consists of different classes such as…

--

--

Matthias Bruns

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