Skip to content

Instantly share code, notes, and snippets.

@scottashipp
Last active December 29, 2015 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottashipp/01e624efdd211515dc8c to your computer and use it in GitHub Desktop.
Save scottashipp/01e624efdd211515dc8c to your computer and use it in GitHub Desktop.
Factory Pattern in Scala
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