57.scala编程思想笔记——使用特征构建系统
欢迎转载,转载请标明出处:http://blog.csdn.net/notbaron/article/details/50447611
源码下载连接请见第一篇笔记。
特征是如此独立且影响微小,可以将问题按照需要分解为大量的小碎片。
例如:
package sodafountain
object Quantity extends Enumeration {
type Quantity= Value
val None,Small, Regular,
Extra,Super = Value
}
import Quantity._
object Holder extends Enumeration {
type Holder =Value
val Bowl,Cup, Cone, WaffleCone = Value
}
import Holder._
trait Flavor
object Syrup extends Enumeration {
case class_Val() extends Val
with Flavor
type Syrup =_Val
valChocolate, HotFudge,
Butterscotch, Caramel = _Val()
}
import Syrup._
object IceCream extends Enumeration {
case class_Val() extends Val
with Flavor
type IceCream= _Val
valChocolate, Vanilla, Strawberry,
Coffee,MochaFudge, RumRaisin,
ButterPecan= _Val()
}
import IceCream._
object Sprinkle extends Enumeration {
case class_Val() extends Val
with Flavor
type Sprinkle= _Val
val None,Chocolate, Rainbow = _Val()
}
import Sprinkle._
trait Amount {
valquant:Quantity
}
trait Taste[F <: Flavor] extends Amount {
val flavor:F
}
case class
Scoop(quant:Quantity, flavor:IceCream)
extends Taste[IceCream]
trait Topping
case class
Sprinkles(quant:Quantity, flavor:Sprinkle)
extends Taste[Sprinkle] with Topping
case class
Sauce(quant:Quantity, flavor:Syrup)
extends Taste[Syrup] with Topping
case class WhippedCream(quant:Quantity)
extends Amount with Topping
case class Nuts(quant:Quantity)
extends Amount with Topping
class Cherry extends Topping
注意:Flavor和Topping 都是标记特征。
在编写代码时,最基本的一条准则是越短的语句越好。
另一条同等重要的准则是消除重复代码。
编译上述代码:
# scalac SodaFountain.scala
然后制作如下代码,可以制作一些甜点:
import com.atomicscala.AtomicTest._
import sodafountain._
import Quantity._
import Holder._
import Syrup._
import IceCream._
import Sprinkle._
case class
Scoops(holder:Holder, scoops:Scoop*)
val iceCreamCone = Scoops(
WaffleCone,
Scoop(Extra,MochaFudge),
Scoop(Extra,ButterPecan),
Scoop(Extra,IceCream.Chocolate))
iceCreamCone is "Scoops(WaffleCone," +
"WrappedArray(Scoop(Extra,MochaFudge), " +
"Scoop(Extra,ButterPecan), " +
"Scoop(Extra,Chocolate)))"
case class MadeToOrder(
holder:Holder,
scoops:Seq[Scoop],
toppings:Seq[Topping])
val iceCreamDish = MadeToOrder(
Bowl,
Seq(
Scoop(Regular, Strawberry),
Scoop(Regular, ButterPecan)),
Seq[Topping]())
iceCreamDish is "MadeToOrder(Bowl," +
"List(Scoop(Regular,Strawberry), " +
"Scoop(Regular,ButterPecan)),List())"
case class Sundae(
sauce:Sauce,
sprinkles:Sprinkles,
whipped:WhippedCream,
nuts:Nuts,
scoops:Scoop*) {
valholder:Holder = Bowl
}
val hotFudgeSundae = Sundae(
Sauce(Regular, HotFudge),
Sprinkles(Regular, Sprinkle.Chocolate),
WhippedCream(Regular), Nuts(Regular),
Scoop(Regular, Coffee),
Scoop(Regular, RumRaisin))
hotFudgeSundae is "Sundae(" +
"Sauce(Regular,HotFudge)," +
"Sprinkles(Regular,Chocolate),"+
"WhippedCream(Regular),Nuts(Regular)," +
"WrappedArray(Scoop(Regular,Coffee), " +
"Scoop(Regular,RumRaisin)))"
其中Scoops是基本的实现,利用它可以创建一个冰淇淋筒或一盘冰淇淋。