Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator vs Visitor Design Pattern and How

Going through the various examples in different articles on Design Patterns available in the internet, I can see that Visitor Pattern is associated with traversing some data structure, usually a tree or hierarchy and I am bit confused since if that's the case we can use the Iterator Pattern as well.

How the Visitor Design Pattern differ from the Iterator Design Pattern? Also how C# implements (emulates) "Double Dispatch" using the Visitor Design pattern? Any thoughts with some code illustrations.

like image 717
Vishnu Y Avatar asked Feb 21 '14 11:02

Vishnu Y


1 Answers

By using the Visitor pattern you decouple the actions performed on some data structure from the specific structure - i.e. you define some algorithm that is not concerned about what data it will be applied on. It was actually originated to solve the problem of modifying the behavior of classes which could not be modified.

The Iterator pattern decouples the exploration of a data structure from the specific structure.

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.

IEnumerable in .NET implements an Iterator pattern. Say you have an Item class with a Visit method that takes an IVisitor interface, which visitors implement, and calls some method from that interface to invoke the visitor action. Then you would use the iterator to visit each item of a collection:

IEnumerable<Item> itemCollection = new List<Item>(...);
IVisitor visitor = new VisitorImplementation();

foreach (Item item in itemCollection)
    item.Visit(visitor);

Regarding your second question, you might find this great MSDN articule on the Visitor pattern and double dispatch useful. It provides a better explanation of the visitor pattern while also being focused on that topic.

like image 109
jnovo Avatar answered Sep 19 '22 01:09

jnovo