Example class diagram

Imagine a media player. Most media players have a play button—when we activate it, it usually changes its appearance and becomes a pause button. Clicking the pause button now also does something different—it pauses the playback and reverts to a play button. This is a good candidate for the state design pattern, where depending on which state the player is in, a different action happens.

The following class diagram shows the classes that are needed to implement this functionality for the play and pause buttons:

Our Playing and Paused implementations set the state to the opposite one and make our player functional. Using ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.