Hei*_*ing 3 class-design scala traits
为了简化我的实际代码,我们假设有两个类,一个是另一个的子类:
class Chair {
val canFold = false;
// ...
}
class FoldableChair extends Chair {
val canFold = true;
// ...
}
Run Code Online (Sandbox Code Playgroud)
在我的实现中,我将有数百个其他子类的Chair或FoldableChair:
class Armchair extends ... {}
class DeckChair extends ... {}
//... etc
Run Code Online (Sandbox Code Playgroud)
对于这些子类中的每一个,假设每个子类都有一个冗长的实现,但我希望能够让它有时扩展Chair并有时扩展FoldableChair - 而不需要复制代码.我想在没有子类本身扩展的情况下这样做.这有可能吗?我需要使用特征来做到这一点吗?
我还希望能够创建子类的特定实例,有时会扩展Chair并有时扩展FoldableChair,但是在实例化时会做出这种选择.这也可能吗?谢谢!
编辑:澄清一下,我真正想要的是:
class Armchair extends Chair {}
class ArmchairFoldable extends FoldableChair {}
Run Code Online (Sandbox Code Playgroud)
但Armchair和ArmchairFoldable的实施完全相同.也就是说,我不想复制他们的实现.
您可以使用实现特征; 即,您与某个类混合并为其他成员提供实现的特征.
例:
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
Run Code Online (Sandbox Code Playgroud)
然后你可以写:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
212 次 |
| 最近记录: |