我不想去斯卡拉,请看下面的代码。
abstract class Pizza() {
def toppings: List[String]
def price: BigDecimal
}
trait Large extends Pizza {
abstract override def price: BigDecimal = super.price * 2
}
trait Cheese extends Pizza {
abstract override def toppings: List[String] = "Cheese" :: super.toppings
abstract override def price: BigDecimal = super.price + 0.5
}
trait Salami extends Pizza {
abstract override def toppings: List[String] = "Salami" :: super.toppings
abstract override def price: BigDecimal = super.price + 1.0
}
class BasePizza extends Pizza {
def toppings = List("Tomato Sauce")
def price = 5.0
}
class MargheritaPizza extends BasePizza with Cheese
class LargeMargheritaPizza extends MargheritaPizza with Large
class SalamiPizza extends MargheritaPizza with Salami
class DoubleCheeseSalamiPizza extends MargheritaPizza with Salami with Cheese
println(reflect.runtime.universe.typeOf[DoubleCheeseSalamiPizza].baseClasses)
// List(class DoubleCheeseSalamiPizza, trait Salami, class MargheritaPizza, trait Cheese, class BasePizza, class Pizza, class Object, class Any) res0: Unit = ()
如何多次添加装饰?例如,一份披萨配双芝士?(如线性化顺序所示
trait Cheese
延长一次)