Vishnu Y
Vishnu Y

Reputation: 2321

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.

Upvotes: 7

Views: 3876

Answers (2)

jnovo
jnovo

Reputation: 5779

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.

Upvotes: 15

Ondrej Janacek
Ondrej Janacek

Reputation: 12626

Iterator is in .NET used for going through collections using loops. It's implemented using IEnumerable and IEnumerator interfaces.

You can find a sample code for Iterator on MSDN.

I know Visitor as a pattern used in cases where you don't want to change domain objects but still be able to run a different logic on them. In .NET I know only about System.Linq.Expressions.ExpressionVisitor which is internally used by LINQ. You wouldn't use the Visitor to enumerate collections and that's the difference I would say.

Upvotes: 2

Related Questions