这是有关面向对象编程的问题,因此它并非专门针对Scala。我需要为具有两种抽象类型的抽象接口编写具体方法。但是我需要以一种允许我调用特定于子类的方法的方式来编写它。我尝试遵循的每个简单解决方案只会导致无法解决的事情陷入困境。如果我丰富了Animal类以使其看起来像绵羊,则Pasture类将无法调用仅绵羊方法。相反,如果我将Farm类丰富起来,使其看起来更像是Pasture,则Sheep类不能调用仅Pasture方法。这是一个恶毒的鸡蛋问题。解决方案很可能隐藏在有关“编程模式”的其中一本教科书中,但我不知道在哪里。你的想法?
// Interface
abstract class Farm {
}
abstract class Animal {
}
abstract class GenericSim {
def simulate( an:Animal , fa:Farm ):Double
}
// Instantiation
class Pasture extends Farm {
private final val size = 23
def getSize:Int = size
}
class Sheep extends Animal {
private var woolContent = 8
def sheer():Int = {
val ret:Array[Int] = Array.ofDim[Int](1)
ret(0) = woolContent
woolContent = 0
ret(0)
}
}
class ShephardSimulator extends GenericSim {
def simulate( an:Animal, fa:Farm ):Double = {
// I need to call fa.getSize() but that does not compile.
// I need to call an.sheer() but that does not compile.
// What is the solution?
0.0
}
}
例如,使用当前设计,您可以使用模式匹配将对象从Animal
投射到Sheep
,从Farm
投射到Pasture
,
class ShepardSimulator extends GenericSim {
def simulate(an: Animal, fa: Farm): Double = {
(an, fa) match {
case (sheep: Sheep, pasture: Pasture) =>
pasture.getSize // ok
sheep.sheer() // ok
0.0
case _ =>
0.0
}
}
}