Last active
December 29, 2015 18:00
-
-
Save scottashipp/01e624efdd211515dc8c to your computer and use it in GitHub Desktop.
Factory Pattern in 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
sealed abstract class Vehicle(val go: String) | |
class HotRod extends Vehicle("Vrooooom!") | |
class Train extends Vehicle("Chooo choooo") | |
class Moped extends Vehicle("Bzzzzzzzzzzz") | |
sealed abstract class Route(val name: String) | |
class Highway extends Route("Interstate") | |
class CityStreet extends Route("Boulevard") | |
class TrainTrack extends Route("Rail") | |
object Vehicle { | |
def apply(r: Route): Vehicle = { | |
r match { | |
case _: Highway => new HotRod | |
case _: CityStreet => new Moped | |
case _: TrainTrack => new Train | |
} | |
} | |
} | |
object SendVehicles extends App { | |
val interstate5 = new Highway | |
val fifthAvenue = new CityStreet | |
val bAndORailroad = new TrainTrack | |
println(s"For the ${interstate5.name} our vehicle sounds like ${Vehicle(interstate5).go}") | |
println(s"For the ${fifthAvenue.name} our vehicle sounds like ${Vehicle(fifthAvenue).go}") | |
println(s"For the ${bAndORailroad.name} our vehicle sounds like ${Vehicle(bAndORailroad).go}") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment