如何在超视construtor参数在运行时(在Java中)

问题描述:

我有以下类和结构(简本)创建子类对象:如何在超视construtor参数在运行时(在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(...) } 

    ... 
} 

现在的问题是,我需要创建用Polygon-Object,Rectangle-Object或Square-Object,取决于构造函数参数以及运行时isSquare(),isRectangle()和isRotated()方法的结果,程序应自动选择应创建哪个对象。例如,如果给定的4个点导致isSquare = true并且isRotated()= false,我想创建Square对象,如果isRotated()= true,我将创建多边形对象。

我研究了关于建造者模式和工厂模式,但我不明白,所以我could'nt实现它为我的问题,我不知道是否有对我来说是更好的解决方案。一些正确的方向和示例的建议或提示可能对我有很大的帮助。我希望你明白我的问题。

我知道,长方形和正方形的构造基本上是相同的,但在这里,那不是话题,以后我会解决它。 ;)

这里是一个UML图向你展示当前的结构,其在德国,所以我翻译的重要组成部分你。 (它不是最终的,我可能会改变它): UML Diagram PNG

感谢您的帮助提前。

这是错误的,我想用一个工厂将是最好的方式(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

+0

好吧,我tryed它,看起来是为我工作。 我应该将我的解决方案添加到我的问题吗? – Rep

+0

这很好,不要忘记选择最佳答案作为“答案”,以便其他人可以从这篇文章中获得帮助。不,您不需要发布解决方案,只需标记最佳答案:)(在选票下面有一张支票) –

据我所知你基本上总是一个多边形对象,所以你可以使用一个工厂为你创建一个多边形对象。要检查您必须使用哪种类型,可以使Polygon类中的方法(isSquare,isRectangle和isRotated)为静态。随后,工厂使用的具体实施多边形来创建多边形对象:

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); 
    } 
}