簡體   English   中英

Java中具有翻轉參數的調用方法

[英]Calling method with flipped parameters in Java

我有幾個Shape的子類:

Rectangle, Circle, etc.

我在每個類中也都有這樣的方法:

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

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

這些方法顯然將是重復的代碼。 我的問題是,如何避免這樣的事情?

簡單的答案是將Circle的交集方法實現為:

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

我想不出更優雅的方法。


將API方法定義為這樣的問題:

public void isIntersecting(Shape) { ... }

是您最終不得不為每個不同形狀的外殼編寫一個“ instanceof”開關的代碼。 重復的代碼仍然存在,並且您已經用可能更脆弱的東西替換了靜態類型。

(AFAIK,沒有通用/有效的算法來測試兩個任意形狀是否相交。尤其是形狀包含曲線時。)

您可以一次實現它們(在類中或作為某個地方的靜態方法),並讓所有方法調用該共享代碼。

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