Skip to content

Instantly share code, notes, and snippets.

@sdb
Created August 26, 2010 22:45
Show Gist options
  • Save sdb/552404 to your computer and use it in GitHub Desktop.
Save sdb/552404 to your computer and use it in GitHub Desktop.
Factory pattern in Scala
abstract class Vehicle(val color: String) {
def price = 100 * factor
def factor: Double
}
class Car(override val color: String) extends Vehicle(color) {
val factor = 1.0
}
class Van(override val color: String) extends Vehicle(color) {
val factor = 1.5
}
object Vehicle {
def apply(typ: String, color: String) = typ match {
case "CAR" => new Car(color)
case "VAN" => new Van(color)
}
}
object FactoryDemo {
def main(args: Array[String]) {
val vehicle = Vehicle(args(0), args(1))
val typ = vehicle match {
case c: Car => "car"
case v: Van => "van"
}
println("A shiny %s %s costs %.0f pesos.".format(vehicle.color, typ, vehicle.price))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment