Beispiel mit Besucher-Muster

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);
    }
}

und nun, hier ist ein Besucher, den ich gemacht:

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();
    }
}

Warum ist dies besser als nur darum, eine öffentliche Eigenschaft-Songs, und dann lassen jede Art von Klasse zu tun alles, was es will?

Diesem Beispiel kommt von dieser post.

Schreibe einen Kommentar