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 ...