Visitor pattern

In this note I will describe a design pattern called “Visitor” or “Visitor”
This pattern belongs to the group of Behavioral patterns.

Let’s think of a problem

This pattern is mainly used to work around the single dispatch limitation in early-binding languages.

Alice X by NFGPhoto (CC-2.0)
Let’s create an abstract class/protocol Band, make a subclass MurpleDeep, create a class Visitor with two methods – one for outputting to the console any descendant of Band, the second for outputting any MurpleDeep, the main thing is that the names (signatures) of the methods are the same, and the arguments differ only in the class. Through the intermediate method printout with the argument Band, create an instance of Visitor and call the visit method for MurpleDeep.
Next is the code in Kotlin:

The output will be “This is Band class

How is that possible?!

Why this happens is described in clever words in many articles, including in Russian, but I suggest you imagine how the compiler sees the code, perhaps everything will become clear right away:

Solving the problem

There are many solutions to this problem, below we will consider a solution using the Visitor pattern.
In the abstract class/protocol we add the accept method with the Visitor argument, inside the method we call visitor.visit(this), after that we add an override/implementation of the accept method to the MurpleDeep class, decisively and calmly violating DRY, we write visitor.visit(this) again.
Final code:

Sources

https://refactoring.guru/ru/ design-patterns/visitor-double-dispatch

Source code

https://gitlab.com/demensdeum/patterns

Leave a Comment

Your email address will not be published. Required fields are marked *