什么是相当于Java构建器模式的Scala? [英] What is the Scala equivalent to a Java builder pattern?
问题描述
新的PizzaBuilder(Size.Large).onTopOf(Base.Cheesy)。与(Ingredient.Ham).build();
使用快速而肮脏的Java方法,每个方法调用都会将构建器实例并返回这个
。不可否认,它涉及更多的打字,在修改之前先克隆构建器。构建方法最终会在构建器状态下重演。
在Scala中实现相同的方法是什么?
如果我想确保 onTopOf(base:Base)
仅被调用一次,然后只有与(成分:Ingredient)
和 build():Pizza
可以被调用,a-la一个定向构建器,我将如何处理这个?
Scala 2.8中Builder模式的另一个替代方法是使用具有默认参数和命名参数的不可变的案例类。它有一点不同,但效果是明智的默认值,所有指定的值和事情只用语法检查指定一次。
以下使用字符串作为简洁的值/速度...
scala> case class Pizza(ingredients:Traversable [String],base:String =Normal,topping:String =Mozzarella)
定义类Pizza
scala> val p1 =披萨(Seq(Ham,Mushroom))
p1:比萨饼(比萨饼(列表(火腿,蘑菇),正常,无烟草)
scala> val p2 = Pizza(Seq(Mushroom),topping =Edam)
p2:Pizza = Pizza(List(Mushroom),Normal,Edam)
scala> val p3 = Pizza(Seq(Ham,Pineapple),topping =Edam,base =Small)
p3:Pizza = Pizza(List(Ham,Pineapple),Small,Edam)
然后,您也可以使用现有的不可变实例作为构建器...
scala> val lp2 = p3.copy(base =Large)
lp2:Pizza = Pizza(List(Ham,Pineapple),Large,Edam)
In the work that I do on a day to day in Java, I use builders quite a lot for fluent interfaces, e.g.: new PizzaBuilder(Size.Large).onTopOf(Base.Cheesy).with(Ingredient.Ham).build();
With a quick-and-dirty Java approach, each method call mutates the builder instance and returns this
. Immutably, it involves more typing, cloning the builder first before modifying it. The build method eventually does the heavy lifting over the builder state.
What's a nice way of achieving the same in Scala?
If I wanted to ensure that onTopOf(base:Base)
was called only once, and then subsequently only with(ingredient:Ingredient)
and build():Pizza
could be called, a-la a directed builder, how would I go about approaching this?
Another alternative to the Builder pattern in Scala 2.8 is to use immutable case classes with default arguments and named parameters. Its a little different but the effect is smart defaults, all values specified and things only specified once with syntax checking...
The following uses Strings for the values for brevity/speed...
scala> case class Pizza(ingredients: Traversable[String], base: String = "Normal", topping: String = "Mozzarella")
defined class Pizza
scala> val p1 = Pizza(Seq("Ham", "Mushroom"))
p1: Pizza = Pizza(List(Ham, Mushroom),Normal,Mozzarella)
scala> val p2 = Pizza(Seq("Mushroom"), topping = "Edam")
p2: Pizza = Pizza(List(Mushroom),Normal,Edam)
scala> val p3 = Pizza(Seq("Ham", "Pineapple"), topping = "Edam", base = "Small")
p3: Pizza = Pizza(List(Ham, Pineapple),Small,Edam)
You can then also use existing immutable instances as kinda builders too...
scala> val lp2 = p3.copy(base = "Large")
lp2: Pizza = Pizza(List(Ham, Pineapple),Large,Edam)
这篇关于什么是相当于Java构建器模式的Scala?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!