Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you decide to use a visitors for your objects?

I always thought an object needs the data and the messages to act on it. When would you want a method that is extrinsic to the object? What rule of thumb do you follow to have a visitor? This is supposing that you have full control of the object graph.

like image 990
unj2 Avatar asked May 12 '10 00:05

unj2


People also ask

When should you use the visitor pattern?

2 Answers. Save this answer. Show activity on this post. The visitor pattern is useful when you want to process a data structure containing different kinds of objects, and you want to perform a specific operation on each of them, depending on its type.

What does a visitor pattern do?

In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures.

What does visit () do in Java?

The accept() method accepts a visitor. It is provided by the Visitable class. The visit() method is called every time when we visit an element. It is implemented by the Visitor class.


1 Answers

The visitor pattern is particularly useful when applying an operation to all elements of a fairly complicated data structure for which traversal is non-trivial (e.g. traversing over the elements in parallel, or traversing a highly interconnected data structure) or in implementing double-dispatch. If the elements are to be processed sequentially and if double-dispatch is not needed, then implementing a custom Iterable and Iterator is usually the better choice, especially since it fits in better with the other APIs.

like image 127
Michael Aaron Safyan Avatar answered Oct 11 '22 16:10

Michael Aaron Safyan