Skip to content

Instantly share code, notes, and snippets.

@haimeili
Created November 3, 2014 16:08
Show Gist options
  • Save haimeili/e3266704475a99287215 to your computer and use it in GitHub Desktop.
Save haimeili/e3266704475a99287215 to your computer and use it in GitHub Desktop.
Factory Method by Scala
Vehicle Interface:
trait Vehicle {
def drive
}
Various implement of Vehicle:
class Car extends Vehicle {
override def drive {
println("car comming")
}
}
class Bus extends Vehicle {
override def drive {
println("bus comming")
}
}
class Truck extends Vehicle {
override def drive {
println("truck comming")
}
}
The most important Thing is below:
object Vehicle {
def apply(kind: String) = kind match {
case "car" = new Car()
case "bus" = new Bus()
case "truck" = new Truck()
}
}
The factory is object, scala uses "apply" because we can ignore .apply when call Vehicle. We only use Vehicle("car") to replace Vehicle.apply("car"). This is the beauty of scala.
Test case:
object Test extends App {
val myVehicle = Vehicle("car")
myVehicle drive//car coming
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment