-
-
Save KushalP/2c2d94f99cc3aca3f84f to your computer and use it in GitHub Desktop.
My take on @flashingpumpkin's PizzaBuilder
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
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