Search code examples
design-patternsvisitor-pattern

Visitor Pattern: Should the visitor or the visited object decide the visiting order?


I've seen examples in both ways, particularly Wikipedia shows an example where the visited object decides the visiting order and I think this is a sounding approach.

I'm in a situation in which I will need several visiting orders so It seems reasonable to let the Visitor decide the visiting order. However, If the visitor is responsible for the visiting order (i.e., for calling the accept method of the object being visited) I could make the visitor just call some visiting method directly (i.e., bypass the call to the visiting object's accept method) and this seems totally contrary to what the pattern proposes..

What is the correct way to implement the visiting pattern and how to deal when we have several different visiting orders?


Solution

  • I believe there is no "one correct way". Correct way is the way that meets your needs.

    A visitor must visit each element of the object structure. The question is, how does it get there? Who is responsible for traversing the object structure? GoF Design Patterns book answers the question as follows:

    1- Often the object structure is responsible for iteration. A collection will simply iterate over its elements, calling the Accept operation on each.

    2- Another solution is to use an iterator to visit the elements.

    3- You could even put the traversal algorithm in the visitor, although you'll end up duplicating the traversal code in each ConcreteVisitor for each aggregate ConcreteElement. The main reason to put the traversal strategy in the visitor is to implement a particularly complex traversal, one that depends on the results of the operations on the object structure.

    So it is fine to let visitor to decide visiting order.