Visitor pattern

In this article I will describe a design pattern called “Visitor”
This pattern refers to the group Behavioral patterns.

Think up a problem

Basically, this pattern is used to bypass the restriction of a single dispatch (“single dispatch”), in languages ​​with early binding.

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

The output will be “This is Band class

WTF (World Taekwondo Federation)

Why this happens is described in buzzwords in many articles, including in Russian, I suggest you present how the compiler sees the code, maybe everything will become clear right away:

Silver bullet

To solve this problem, there are many solutions, then consider the solution using the Visitor pattern.
We add the accept method with the Visitor argument to the abstract class/protocol, call visitor.visit(this) inside the method, then add the override/implementation of the accept method to the MurpleDeep class, break DRY decisively and quietly, write visitor.visit(this).
The resulting code:

Documentation

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

Source code

https://gitlab.com/demensdeum/patterns