U
U
user_of_toster2021-03-24 12:49:30
OOP
user_of_toster, 2021-03-24 12:49:30

What is the essence of the "visitor" pattern?

1) Transferring some function of the subclass tree to a separate class - when it is impossible to implement the method directly in the subclass tree, the method is moved to a separate class.

2) Double dispatching - the element itself calls the desired method in the visitor. (Replacing the conditional statements ̶p̶o̶l̶i̶m̶o̶r̶f̶i̶z̶m̶o̶m̶ with calling the desired method)
They say that double dispatch is not the main idea .

So what's the point - we just move the function out of the subclass tree into a separate class? Is this the essence of the pattern? Or is it still about replacing conditional operators with a method call in the visitor?

Are we violating the OCP?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
koperagen, 2021-03-25
@user_of_toster

Its essence is that it allows you to be sure that you have processed all possible subtypes of some type. Well, let's say if there is `class Node`, `class Leaf1 : Node`, `class Leaf2 : Node`, then the client code could be written like this

if (node instanceof Node) {
...
} else of (node instanceof Leaf1) {
...
}

In general, the compiler will not swear if you skip checking for instanceof Leaf2. If the task implies the obligation to process all existing subtypes, then you will have to follow this yourself. I don’t really want to, given that there can be 40 heirs in the class hierarchy of the syntax tree of some language.
In another way, the goal of the visitor can be formulated as "a stronger contract between the module (anything that defines a visitor) and the client (anything that implements it)." The module insists that you be able to process each subtype somehow in your own way and provides a convenient tool for this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question