Skip to content

Instantly share code, notes, and snippets.

@KushalP
Forked from flashingpumpkin/Builder.scala
Created July 18, 2014 11:59
Show Gist options
  • Save KushalP/2c2d94f99cc3aca3f84f to your computer and use it in GitHub Desktop.
Save KushalP/2c2d94f99cc3aca3f84f to your computer and use it in GitHub Desktop.
My take on @flashingpumpkin's PizzaBuilder
case class Pizza(dough: String, sauce: String, topping: String) {
override def toString: String = {
"Dough:" + dough + " Topping:" + topping + " Sauce:" + sauce
}
}
abstract class PizzaBuilder {
def withDough(dough: String): PizzaBuilder
def withSauce(sauce: String): PizzaBuilder
def withTopping(topping: String): PizzaBuilder
def build: Pizza
}
case class BuildPizza(dough: Option[String], sauce: Option[String], topping: Option[String]) extends PizzaBuilder {
override def withDough(dough: String): PizzaBuilder = {
BuildPizza(Some(dough), sauce, topping)
}
override def withSauce(sauce: String): PizzaBuilder = {
BuildPizza(dough, Some(sauce), topping)
}
override def withTopping(topping: String): PizzaBuilder = {
BuildPizza(dough, sauce, Some(topping))
}
override def build: Pizza = Pizza(dough.getOrElse("No dough"),
sauce.getOrElse("No sauce"),
topping.getOrElse("No topping"))
}
object PizzaBuilderExample {
def main(args: Array[String]) = {
val hawaiianPizza = BuildPizza(None, None, None).withDough("cross")
.withTopping("ham + pineapple").withSauce("mild").build
println("Hawaiian Pizza:" + hawaiianPizza)
}
}
PizzaBuilderExample.main(Array())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment