Created
August 26, 2010 22:45
-
-
Save sdb/552404 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
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