shou3301
shou3301

Reputation: 214

Object-oriented design - pause function

I was trying to sharp my OOD thinking. Here is my question.

Suppose you want to design a music mp3 player. And I got a class with a collection of playlists.

class Player {
    Map<String, List<Song>> playlists;    // <Name, PlayList>
    public void play (Song song) {
        // decode song
        // play song
    }
    public void play (String playlistName) {
        // play a playlist
        for (Song song : playlists.get(playlistName)) {
            play (song);
        }
    }
    public void stop () {
        // stop playing
    }
    public void pause () {
        // pause, resume playing the last song when hit play again
    }
}

Let's assume "Song" already contains all the metadata of a song. All the functionalities of methods have been described. I got stucked when I was trying to realize the "pause" method. What would you do to realize this?

Thanks!

Upvotes: 1

Views: 596

Answers (3)

Philipp
Philipp

Reputation: 69663

It seems to me like th play method blocks until the song has finished. It is a completely single-threaded design. When you design your application like that, it can't react to user input while a song is playing (unless you place an input handler into the playing loop).

In a real-world application, the play() method would start playing the song in a separate thread (many audio APIs will do that for you, so that you don't have to mingle with multi-threading) and then return, so that the application can stay responsible while a song is playing.

That way the pause and resume methods would then interact with the thread which plays the song.

Upvotes: 1

DarthVader
DarthVader

Reputation: 55022

Look into state pattern. Which you will store state of the player. When you hit pause and play you will know the state of the player.

Upvotes: 6

Ameen
Ameen

Reputation: 2586

I would have a Song member variable that tracks the currently playing song. If there is nothing playing, the value would be set to null. When you pause a Song, you simply call the Pause method on the Song class if the currently playing Song is not null. The Song class in turn can track where in the song (in terms of minutes) it is and figure out how a resume would work.

Upvotes: 2

Related Questions