Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Builder pattern (Design patterns in Scala)

More than 5 years have passed since last update.

abstract class Product

abstract class PizzaBuilder {
var dough: String
var sauce: String
var topping: String

def withDough(dough: String): PizzaBuilder
def withSauce(sauce: String): PizzaBuilder
def withTopping(topping: String): PizzaBuilder

def build: Product
}

class Pizza(builder: PizzaBuilder) extends Product {
val dough: String = builder.dough
val sauce: String = builder.sauce
val topping: String = builder.topping

override def toString: String = {
"Dough:" + dough + " Topping:" + topping + " Sauce:" + sauce
}
}

class Cook extends PizzaBuilder {
var dough: String = ""
var sauce: String = ""
var topping: String = ""

override def withDough(dough: String): PizzaBuilder = {
this.dough = dough
this
}

override def withSauce(sauce: String): PizzaBuilder = {
this.sauce = sauce
this
}

override def withTopping(topping: String): PizzaBuilder = {
this.topping = topping
this
}

override def build: Product = new Pizza(this)
}

object PizzaBuilderExample {
def main(args: Array[String]) = {
val hawaiianCook = new Cook().withDough("cross").withTopping("ham+pineapple").withSauce("mild")
val hawaiianPizza = hawaiianCook.build
println("Hawaiian Pizza:" + hawaiianPizza)
}
}

PizzaBuilderExample.main(Array())

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away