We have a MediaPlayer interface and a concrete class AudioPlayer implementing the MediaPlayer interface. AudioPlayer can play mp3 format audio files by default.
We are having another interface AdvancedMediaPlayer and concrete classes implementing the AdvancedMediaPlayer interface. These classes can play vlc and mp4 format files.
We want to makeAudioPlayer to play other formats as well. To attain this, we have created another classMediaAdapter which implements theMediaPlayer interface and usesAdvancedMediaPlayer objects to play the required format.
AudioPlayer uses the classMediaAdapter passing it the desired audio type without knowing the actual class which can play the desired format.Main class, our demo class will useAudioPlayer class to play various formats.
- Create an interface MediaPlayer having an abstract method
public void play(String audioType, String fileName);
- Now create another interface AdvancedMediaPlayer having two abstract methods
public void playVlc(String fileName);
public void playMp4(String fileName);
- Now create concrete classes VLCPlayer , MP4Player both implements the AdvancedMediaPlayer interface.
- Create another class MediaAdapter which implements the MediaPlayer Interface and also carry an object of AdvancedMediaPlayer as a data member.
AdvancedMediaPlayer advancedMusicPlayer;
Provide a constructor as
public MediaAdapter(String audioType)
Now if audiotype is “VLC” then makes
advancedMusicPlayer = new VlcPlayer();
otherwise if type is MP4 then you have to create mp4 object as
advancedMusicPlayer = new Mp4Player();
Also implements the play method of MediaPlayer Interface which checks the type of audio if its VLC then it will play VLC file otherwise it will plays MP4 file.
- Create a concrete class AudioPlayer which implements the MediaPlayer Interface. And have an instance of Media Adapter class as
MediaAdapter mediaAdapter;
This class will also implements the play method of the MediaPlayer Interface but this it will checks all formats if type is mp3 then it will play mp3 file, if the type is MP4 or VLC then it will call the play method of MediaAdapter class.
- Now in demo class write the following and observe the output
AudioPlayer audioPlayer = new AudioPlayer();
audioPlayer.play("mp3", "beyond the horizon.mp3");
audioPlayer.play("mp4", "alone.mp4");
audioPlayer.play("vlc", "far far away.vlc");
audioPlayer.play("avi", "mind me.avi");
Explain the working in your own words.