Scala:使用工厂进行子类化

时间:2013-10-21 09:44:14

标签: scala traits

假设我有两个特征,其中一个是另一个工厂:

trait BaseT {
  val name: String
  def introduceYourself() = println("Hi, I am " +name)
  // some other members ...
}
trait BaseTBuilder {
  def build: BaseT
}

现在,我想扩展BaseT:

trait ExtendedT extends BaseT {
  val someNewCoolField: Int
  override def introduceYourself() = {
    super.introduceYourself()
    println(someNewCoolField)
  }
  // some other extra fields

假设我知道如何初始化新字段,但我想使用BaseTBuilder来初始化超类成员。是否有可能创建一个能够以某种方式实例化ExtendedT的特征?这种方法显然失败了:

trait ExtendedTBuilder { self: TBuilder =>
  def build: ExtendedT = {
    val base = self.build()
    val extended = base.asInstanceOf[ExtendedT] // this cannot work
    extended.someNewCoolField = 4  // this cannot work either, assignment to val
    extended
  }
  def buildDifferently: ExtendedT = {
    new ExtendedT(4)  // this fails, we don't know anything about constructors of ExtendedT
  }
  def build3: ExtendedT = {
    self.build() with {someNewCoolField=5} //that would be cool, but it cannot work either
  }
}

我想拥有这样一组特征(或对象),当有人提供BaseTBaseTBuilder的具体实现时,我可以通过编写实例化ExtendedT

val extendedBuilder = new ConcreteBaseTBuilder with ExtendedTBuilder
val e: ExtendedT = extendedBuilder.build

ExtendedT可以包含BaseT类型的字段,但是它需要手动代理所有必要的方法和字段,这在我看来是违反DRY原则的。怎么解决?

1 个答案:

答案 0 :(得分:0)

如何在ExtendBaseTBuilder中创建ExtendBaseT实例

trait ExtendBaseTBuilder { self : BaseTBuilder =>
  def build: ExtendBaseT = {
    new ExtendBaseT {
      val someNewCoolField: Int = 3
    }
  }

}