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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With