多态类似的参数处理 - 简单的OO?

use*_*401 5 java polymorphism overloading

我确信之前一定要问过,但我似乎找不到类似的例子.我理解多态性和方法重载很好,但这是一个看似简单的场景,其解决方案让我感到惊讶:

假设我有一个带有几个派生类的基类.我会在这个例子中使用形状

base Shape
derived Circle extends Shape
derived LineSeg extends Shape
Run Code Online (Sandbox Code Playgroud)

等等

现在,shape有一个名为intersect(other)的方法,它测试另一个形状以查看它们是否相交.通过多态性,很容易看出Circle,LineSeg等如何实现自己的"交叉"方法,并且通过方法重载,我可以轻松实现所有需要的组合.例如,

Circle.intersect(LineSeg)
Circle.intersect(Circle)
LineSeg.intersect(Circle)
Run Code Online (Sandbox Code Playgroud)

等等

到现在为止还挺好.

问题是,如果我保留一个中心的形状列表,我想这样做:

for some shape s
Foreach shape in Shapes
  if (s.intersect(shape)) - do something
Run Code Online (Sandbox Code Playgroud)

目前,我不确定这是怎么可能的,因为方法重载选择"intersect"方法来匹配基类型Shape,而不是相应的参数类型.如果没有if-else链检查类型和向下转换,我怎么能做到这一点?

顺便说一句,我使用的是Java,但我不确定该语言是否完全相关,因为它似乎是一个基本的设计问题.看起来如此简单,我错过了什么?

谢谢!


解决了下面(谢谢!),请参阅那里的详细信息.基本上,通过在派生类中调用然后调用适当的方法(访问者模式?),您可以使用"this"关键字来调用正确的交叉方法,因为它具有所需的正确类型.

con*_*oly 4

我的第一个想法是访问者模式,几乎为每个 Shape 提供两个方法,一个我将调用intersect(Shape),每个 Shape 类型一个doIntersect()方法。

它看起来像这样:

interface Shape {
    public abstract Intersection intersect(Shape other);

    public abstract Intersection doIntersect(Circle circle);

    public abstract Intersection doIntersect(LineSeg line);
}
class LineSeg implements Shape {
    @Override
    public Intersection intersect(Shape other) {
        return other.doIntersect(this);
    }

    Intersection doIntersect(Circle circle) {
        // Code to intersect with Circle
    }

    Intersection doIntersect(LineSeg other) {
       // Code to intersect with another Lineseg
    }
}

class Circle implements Shape {
    @Override
    public Intersection intersect(Shape other) {
        return other.doIntersect(this);
    }

    public Intersection doIntersect(Circle other) {
        // Code to intersect with another Circle
    }

    public Intersection doIntersect(LineSeg segment) {
        // Code to intersect with LineSeg
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能希望 doIntersect 方法是包私有的,或者选择与这些方法不同的名称。