scala:重用子类实现作为两个不同类的子类?

时间:2011-04-29 08:26:17

标签: scala class-design traits

为了简化我的实际代码,我们假设有两个类,一个是另一个的子类:

class Chair {
   val canFold = false;
   // ...
}

class FoldableChair extends Chair {
   val canFold = true;
   // ...
} 

在我的实现中,我可能会有数百个其他的Chair或FoldableChair子类:

class Armchair extends ... {}
class DeckChair extends ... {} 
//... etc

对于每个子类,假设每个子类都有一个冗长的实现,但我希望能够让它有时扩展Chair并有时扩展FoldableChair - 而不重复代码。我想在没有子类本身扩展的情况下这样做。这有可能吗?我是否需要使用特征来做到这一点?

我还希望能够创建子类的特定实例,有时会扩展Chair并有时扩展FoldableChair,但是在实例化时会做出选择。这也可能吗?谢谢!

编辑:澄清一下,我真正想要的是:

class Armchair extends Chair {}

class ArmchairFoldable extends FoldableChair {}

但Armchair和ArmchairFoldable的实施完全相同。也就是说,我不想重复他们的实现。

1 个答案:

答案 0 :(得分:5)

您可以使用实施特征;即,您与某个类混合并为其他成员提供实施的特征。

示例:

class Chair {
   // you can use a def rather than a val as it's constant and
   // and doesn't need to occupy a field
   def canFold = false

   // ...
}

class FoldableChair extends Chair {
   override def canFold = true
   // ...
}

trait Extensible extends Chair {
    // this trait extends Chair to mean that it is only
    // applicable to Chair or subclasses of Chair
    def extend = /* ... */
}

class FoldableExtensibleChair extends FoldableChair with Extensible

然后你可以写:

val a = new Chair // bare-bones chair

// decide at creation time that this one is extensible
val b = new Chair with Extensible

val c = new FoldableChair // non extensible

// use predefined class which already mixes in Extensible
val d = new FoldableExtensibleChair