簡體   English   中英

如何在運行時根據構造函數參數在超類中創建子類對象(在Java中)

[英]How to create subclass objects in superclass depending on construtor parameters at runtime (in Java)

我具有以下類和結構(簡化版):

public abstract class AbstractGeoObj {
    private Point position;
    ...
    public abstract calcArea();
    public abstract calcPerimeter();
    ...
    some getter
    ...
    some setter
    ...
}

public class Polygon extends AbstractGeoObj implements InterfaceMove {

    private LinkedList<Point> edges;

    public Polygon(LinkedList<Point> points) {
        //here i want to check the conditions and create the right Object
        //but i think this is the wrong way to do it
    }
    ...

    private boolean isSquare(List<Points> points) { ... }

    private boolean isRectangle(List<Points> points) { ... }

    private boolean isRotated(List<Points> points) { ... }

}

public class Rectangle extends Polygon implements InterfaceMove {

    public Rectangle(Point a, Point b, Point c, Point d) {}
    public Rectangle(Point[] points) { this(...) }
    public Rectangle(LinkedList<Piont> points) { this(...) }

    ...
}

public class Square extends Polygon implements InterfaceMove {

    public Square(Point a, Point b, Point c, Point d) {}
    public Square(Point[] points) { this(...) }
    public Square(LinkedList<Piont> points) { this(...) }

    ...
}

現在的問題是,我需要根據構造函數參數以及運行時程序中的isSquare(),isRectangle()和isRotated()方法的結果來創建Polygon-Object,Rectangle-Object或Square-Object。應該自動選擇應該創建哪個對象。 例如,如果給定的4個點導致isSquare = true和isRotated()= false,則我想創建方形對象;如果isRotated()= true,則我將始終創建多邊形對象。

我研究了“構建器模式”和“工廠模式”,但是我不了解它,因此無法為我的問題實施它,而且我不知道是否有更好的解決方案適合我。 正確方向的一些建議或提示以及示例,可能對我有很大幫助。 希望您了解我的問題。

我知道Rectangle和Square的構造函數基本相同,但是那不是這里的主題,我稍后會解決。 ;)

這是一個UML圖,向您顯示當前結構,以德語顯示,因此我為您翻譯了重要部分。 (它不是最終的,我可能會更改): UML圖PNG

感謝您的幫助。

是錯誤的,我認為使用Factory是最好的方法( https://en.wikipedia.org/wiki/Factory_method_pattern ),因為您可以使用一種更常見的方法,因為構造函數的作用不是確定哪種對象要創建,它的作用是創建應該構造的對象。

創建一個類:

class ShapeFactory{
    public static SuperClass getShape(params...){
        if(cond1){return new WhateverSubClass1;}
        else if(cond2){return new WhateverSubClass2;}
        ... (etc for all subclass cases)
    }
}

編輯:遠程參考: http : //www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm

據我了解,您基本上總是有一個多邊形對象,因此您可以使用為您創建一個多邊形對象的工廠。 要檢查必須使用哪種類型,可以在Polygon類中使方法(isSquare,isRectangle和isRotated)靜態。 然后工廠使用Polygon的具體實現來創建Polygon Object:

class PolygonFactory(List<Point> points)
{

  public static Polygon createPolygon(List<Point> points)
  {
    if(Polygon.isSquare(points)
      return new Square(points);
    if(Polygon.isRectangle(points)
      return new Rectangle(points);

    return new Polygon(points);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM