简体   繁体   English

Java中具有翻转参数的调用方法

[英]Calling method with flipped parameters in Java

I have a few subclasses of Shape: 我有几个Shape的子类:

Rectangle, Circle, etc.

I also have a methods in each class like this: 我在每个类中也都有这样的方法:

class Rectangle extends Shape{
    public void isIntersecting(Circle circle){ ... }  
}

class Circle extends Shape{
    public void isIntersecting(Rectangle rectangle){ ... }  
}

These methods obviously would be repeated code. 这些方法显然将是重复的代码。 My question is, how do I avoid something like this? 我的问题是,如何避免这样的事情?

The simple answer is to implement (for instance) Circle's intersection method as: 简单的答案是将Circle的交集方法实现为:

public void isIntersecting(Rectangle rectangle) {
    rectangle.isIntersecting(this);
}

I can't think of a more elegant method. 我想不出更优雅的方法。


The problem with defining the API method as this: 将API方法定义为这样的问题:

public void isIntersecting(Shape) { ... }

is that you end up having to code an "instanceof" switch with a case for each of the different shapes. 是您最终不得不为每个不同形状的外壳编写一个“ instanceof”开关的代码。 The repetitious code is still there, and you've replaced the static typing with something that is potentially more fragile ... 重复的代码仍然存在,并且您已经用可能更脆弱的东西替换了静态类型。

(AFAIK, there is no general / efficient algorithm for testing if two arbitrary shapes intersect. Especially if the shapes involve curved lines.) (AFAIK,没有通用/有效的算法来测试两个任意形状是否相交。尤其是形状包含曲线时。)

You could implement them once (in either class or as a static method somewhere) and have all methods call that shared code. 您可以一次实现它们(在类中或作为某个地方的静态方法),并让所有方法调用该共享代码。

class Rectangle extends Shape{
   public boolean isIntersecting(Circle circle){ 
      return Shapes.isIntersecting(this, circle);
   }  
} 

class Circle extends Shape{
   public boolean isIntersecting(Rectangle rectangle){
       return Shapes.isIntersecting(rectangle, this);
   }  
}

class Shapes{
    static boolean isIntersecting(Rectangle rectangle, Circle circle){
       // implementation goes here
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM