0

While studying the visitor design pattern i found this phrase:

You can use Visitor along with Iterator to traverse a complex data structure and execute some operation over its elements, even if they all have different classes.

Visitor design pattern

While searching on the internet if it was a good idea I found different opinions. Some said that you can combine the two patterns:

You can perfectly combine both: use an iterator to move over each item of a data structure and pass a visitor to each item so that an external responsible performs some operation of the item.

iterator vs visitor

Others said that you can but it depends on the complexity of the operation:

The Visitor is not as such "unneeded" if you have an Iterator. It depends on the complexity of the operation(s) you want to apply to the items you are iterating over.

iterator and visitor

I am wondering in which situation it is useful to have such a combination of patterns. What kind of operation is considered complex ?

  • If you are applying the same operation to each element, or all the elements are of the same type, you don't need a visitor. You need a visitor when you want to select different operations depending on the type of element. – JacquesB Jan 24 at 18:00
  • @JacquesB so if we have a collection of BaseObject containing objects of type Derived1 and Derived2 and want to perform some kind of operation, implemented differently based on the real type of the object in the collection then we can use the visitor ? – Zethel Jan 24 at 18:11
  • Exactly. The comment about complexity is just that if you only have a few different objects, it might be simpler to just use an if to select the appropriate operation, rather than a full blown visitor pattern. – JacquesB Jan 24 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.