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);
}
}
,現在這裏有一個觀衆我做:實例與訪問者模式
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();
}
}
爲什麼這比任何只是把公共財產的歌曲,然後讓任何類型的類用它做什麼都好,它想要?
本示例來自於此post。