繁体   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