【发布时间】:2011-02-06 11:10:42
【问题描述】:
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();
}
}
为什么这比仅仅放置一个公共属性 Songs 然后让任何类型的类做任何它想做的事情更好?
这个例子来自这个post。
【问题讨论】:
标签: c# design-patterns oop