Tu sei qui

State Design Pattern in scala

GianlucaBove.it

...just another technical blog...

Di seguito un esempio di implementazione dello State Design Pattern in Scala.

/**
  * Created by gianluca on 15/05/17.
  */
trait State[T] {
  def press(context: T)
}
 
class Auto extends State[DriveSelect] {
  override def press(context: DriveSelect): Unit = {
    println("go Comfort")
    context.setState(new Comfort)
  }
}
class Comfort extends State[DriveSelect] {
  override def press(context: DriveSelect): Unit = {
    println("go Dynamic")
    context.setState(new Dynamic)
  }
}
 
class Dynamic extends State[DriveSelect] {
  override def press(context: DriveSelect): Unit = {
    println("go Efficiency")
    context.setState(new Efficiency)
  }
}
 
class Efficiency extends State[DriveSelect] {
  override def press(context: DriveSelect): Unit = {
    println("go Individual")
    context.setState(new Individual)
  }
}
 
class Individual extends State[DriveSelect] {
  override def press(context: DriveSelect): Unit = {
    println("go Auto")
    context.setState(new Auto)
  }
}
 
 
case class DriveSelect() {
  private var state: State[DriveSelect] = new Auto
  def pressButton(): Unit = {
    state.press(this)
  }
  def setState(state: State[DriveSelect]): Unit = {
    this.state = state
  }
 
}
 
object MainApp extends App {
 
  val driveSelect = DriveSelect()
  driveSelect.pressButton()
  driveSelect.pressButton()
  driveSelect.pressButton()
  driveSelect.pressButton()
  driveSelect.pressButton()
  driveSelect.pressButton()
  driveSelect.pressButton()
  driveSelect.pressButton()
  driveSelect.pressButton()
  driveSelect.pressButton()
  driveSelect.pressButton()
  driveSelect.pressButton()
 
}

Output:

go Comfort
go Dynamic
go Efficiency
go Individual
go Auto
go Comfort
go Dynamic
go Efficiency
go Individual
go Auto
go Comfort
go Dynamic