Challenge: Visitor Pattern

In this challenge, you have to implement the visitor pattern to solve the given problem.

Problem statement

In this challenge, you need to implement the visitor pattern to separate Rock music from the other genres of music by creating a separate playlist. You need to implement the RockMusicVisitor class for this purpose. As you can see, it contains the visit method; this should return the rock music playlist.

Note: the rock music playlist only needs to contain the names of the songs, not the entire Song object.

Next, you need to implement a Song class. A Song object will have the following properties: name and genre. You also need to define the two functions: getName and getGenre.

Lastly, you need to implement the MusicLibrary class. It should store a list of all the songs regardless of the genres. You need to implement the addSong function to add a song and accept function to allow the RockMusicVisitor to visit the music library.

Input

The accept function is called with RockMusicVisitor as a parameter

Output

A playlist containing names of all the rock songs from the library is returned.

Sample input

var rockMusicVisitor = new RockMusicVisitor()
var song1 = new Song("Bohemian Rhapsody","Rock")
var song2 = new Song("Stair way to Heaven","Rock")
var song3 = new Song("Opps I did it again", "Pop")
var song4 = new Song("Crazy", "Country")
var musicLibrary = new MusicLibrary()
musicLibrary.addSong(song1)
musicLibrary.addSong(song2)
musicLibrary.addSong(song3)
musicLibrary.addSong(song4)
console.log(musicLibrary.accept(rockMusicVisitor))

Sample output

["Bohemian Rhapsody","Stair way to Heaven"]

Challenge #

Take a close look and design a step-by-step solution before jumping on to the implementation. This problem is designed for your practice, so try to solve it on your own first. If you get stuck, you can always refer to the solution provided. Good Luck!

Press + to interact
class RockMusicVisitor{
//write your code here
visit(){}
}
class Song{
//write your code here
getName(){}
getGenre(){}
}
class MusicLibrary{
//write your code here
addSong(){}
accept(){}
}

Let’s discuss the solution in the next lesson.