public class Song {
public string Genre { get; protected set; }
public string Name { get; protected set; }
public string Band { get; protected set; }
public Song(string name, string band, string genre) {
Name = name;
Genre = genre;
Band = band;
}
}
public interface IMusicVisistor
{
void Visit(List<Song> items);
}
public class MusicLibrary {
List<Song> _songs = new List<Song> { ...songs ... };
public void Accept(IMusicVisitor visitor) {
visitor.Visit(_songs);
}
}
and now here's one Visitor I made:
public class RockMusicVisitor : IMusicVisitor {
public List<Song> Songs { get; protected set; }
public void Visit(List<Song> items) {
Songs = items.Where(x => x.Genre == "Rock").ToList();
}
}
Why is this any better than just putting a public property Songs and then letting any kind of class do with it anything that it wants to?
This example comes from this post.
Visitor pattern may be used for iteration over container-like data structures just like Iterator pattern but with limited functionality. For example, iteration over a directory structure could be implemented by a function class instead of more conventional loop pattern.
Visitor design pattern is one of the behavioral design patterns. It is used when we have to perform an operation on a group of similar kind of Objects. With the help of visitor pattern, we can move the operational logic from the objects to another class.
These design patterns are about organizing different classes and objects to form larger structures and provide new functionality. Structural design patterns are Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Private Class Data, and Proxy.
The Visitor pattern suggests that you place the new behavior into a separate class called visitor, instead of trying to integrate it into existing classes.
It is mainly because the example is a bad example of the visitor pattern. The purpose of the visitor pattern is to add common functionality to a group of objects without having to derive from the same class. It lets you keep adding functionality to classes without having to change the classes themselves. The longer fruit example in the answer that you quoted is a better explanation of the visitor pattern.
Read the quoted wikipedia article, for the visitor to pay off you should have a group of classes. In you case different classes are not really warranted so there is no need for the visitor pattern. Given a more heterogeneous class structure the visitor pattern might become useful.
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