Code example

Let's have a look at the code for the class diagram that we showed previously. First of all, let's see the State trait:

trait State[T] {  def press(context: T)}

It is really simple and allows the extending classes to implement the press method. We have two implementations according to our class diagram:

class Playing extends State[MediaPlayer] {  override def press(context: MediaPlayer): Unit = {    System.out.println("Pressing pause.")    context.setState(new Paused)  }}class Paused extends State[MediaPlayer] {  override def press(context: MediaPlayer): Unit = {    System.out.println("Pressing play.")    context.setState(new Playing)  }}

We have made them simple and they only print a relevant message and then change the current state to the ...

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.