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

标签 java polymorphism overloading

我确定之前一定有人问过这个问题,但我似乎找不到类似的例子。我很了解多态性和方法重载,但这是一个看似简单的场景,但有一个让我逃避的解决方案:

假设我有一个包含多个派生类的基类。我将在此示例中使用形状

base Shape
derived Circle extends Shape
derived LineSeg extends Shape

等等

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

Circle.intersect(LineSeg)
Circle.intersect(Circle)
LineSeg.intersect(Circle)

等等

到目前为止还不错。

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

for some shape s
Foreach shape in Shapes
  if (s.intersect(shape)) - do something

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

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

谢谢!


已在下面解决(谢谢!),请参阅此处的详细信息。基本上,通过在派生类中调用适当的方法(访问者模式?)中的回调,您可以使用“this”关键字来调用适当的相交方法,因为它具有所需的适当类型。

最佳答案

我的第一个想法是访问者模式,几乎为每个 Shape 提供了两个方法,一个我称为 intersect(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
    }
}

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

关于java - 类似多态的参数处理 - 简单的 OO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16640765/

相关文章:

java - 从 Java 进程运行时找不到 mount.exe

Java 参数,终端与进程

java - 如果对支付处理器的 API 调用超过 60 秒则中断

c++ - 如何返回从抽象类派生的类的对象?

c# - 重载或可选参数之间的性能差异?

c++ - 我可以获取在重载的新运算符中使用新运算符的对象类型吗?

java - JMSTemplate 生产者是否为每条消息打开一个线程?

java - 检查消息类型时避免 instanceof

提升映射器或记录框架中的继承

java - Java 是否支持默认参数值?