What's the difference between using the Visitor pattern and a separate class?
Asked Answered
C

1

1

I would like to know what is the difference between the Visitor pattern and using a static method to execute code in separation.

Let's take a look at an example where I might call the Visitor pattern:

  new AnalyticsVisitor.accept(myClass); 

and this when called in from myClass for example, would move the work into a visitor to execute. It would even garbage collect faster if it's memory intensive.

Now lets take a look at using a simple method to achieve more or less the same thing:

  new AnalyticsManager.execute(myClass);

Have I achieved the same thing?

  1. I have code separation.
  2. I can apply this to several data structures
  3. I can add info to legacy code without changing it.

So why use the Visitor pattern instead of just a class (unless for double dispatch)?

Crescentic answered 29/8, 2018 at 3:2 Comment(0)
S
3

This question is still a little confused. I suspect you haven't understood the goal of the Visitor pattern.

As discussed here the visitor pattern is useful when you have complex data structure (such as a parse tree) that is relatively stable (in terms of development), but you want to be able to keep adding new operations on all of its elements. This is clumsy with standard OO techniques.


The technology the visitor pattern is based on is double-dispatch, so when you say "Why use the Visitor pattern unless for double-dispatch?" you are effectively saying "Why use the visitor pattern?"


Your example code only includes the client, so it isn't clear what your new technique actually offers.

The supplied code appears to be backwards for a real visitor pattern. It should be:

my_datastructure.accept(analytics_visitor);

where analytics_visitor inherits from MyDataStructureVisitor, and supplies individual methods for each of the element types that the data structure can hold.


As for the achievements:

  1. "Code separation" is a vague term. The visitor pattern allows the data structure to be defined without all the the operations (putative methods) to be defined. Instead, they can be defined separately - with a cost of poorer encapsulation.)

  2. It isn't clear what it means to apply a visitor pattern to several data structures. Each visitor class is associated with one data structure.

  3. The goal isn't to add 'info' to legacy code. It is to add operations to legacy code.

Saddleback answered 29/8, 2018 at 6:25 Comment(1)
i fixed some syntax errors in my statement. thank you for your input though. good ideas.Crescentic

© 2022 - 2024 — McMap. All rights reserved.