Example with Visitor Pattern
Posted
by devoured elysium
on Stack Overflow
See other posts from Stack Overflow
or by devoured elysium
Published on 2010-04-10T10:16:03Z
Indexed on
2010/04/10
10:23 UTC
Read the original article
Hit count: 435
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.
© Stack Overflow or respective owner