Created
November 3, 2014 16:08
-
-
Save haimeili/e3266704475a99287215 to your computer and use it in GitHub Desktop.
Factory Method by Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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