使用重载方法的动态调度(运行时多态),而不使用instanceof

McT*_*cTi 5 java oop polymorphism design-patterns multiple-dispatch

我要救的对象Arc,并Line在一个ArrayList中,然后利用这两者的交集.问题是如何演员ij原作.我知道这instanceof有效,但这将是最脏的方法.

public class Intersection {
    public static boolean intersect(ArrayList<Curve> list1, ArrayList<Curve> list2) {
        for (Curve i : list1) {
            for (Curve j : list2) {
                if (i.intersection(j).length > 0) 
                    return true;
            }
        }
        return false;
    }
}

public abstract class Curve {
    public Point[] intersection(Curve c) {
        return new Point[] {};
    }
}

public class Line extends Curve {
    public Point[] intersection(Line l) {
        // returns intersection Point of this and l
    }

    public Point[] intersection(Arc a) {
        // returns intersection Point(s)
    }
}

public class Arc extends Curve {
    public Point[] intersection(Line l) {
        // return intersection Point(s) of this and l
    }

    public Point[] intersection(Arc a) {
        // returns intersection Point(s)
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Era*_*ran 1

由于每个子类已经必须了解其他子类(例如,Arc必须了解该类Line才能实现ArcLine交集),因此使用instanceof.

在每个子类中,您可以重写基类的public Point[] intersection(Curve c)方法并将实现分派给重载方法之一。

例如:

public class Arc extends Curve {    
    @Override
    public Point[] intersection(Curve c) {
        if (c instanceof Line)
            return instersection ((Line) c);
        else if (c instanceof Arc)
            return intersection ((Arc) c);
        else
            return an empty array or null, or throw some exception
    }

    public Point[] intersection(Line l) {
        // return intersection Point(s) of this and l
    }

    public Point[] intersection(Arc a) {
        // returns intersection Point(s)
    }
}
Run Code Online (Sandbox Code Playgroud)

这样您就不必更改public static boolean intersect(ArrayList<Curve> list1, ArrayList<Curve> list2)方法中的任何内容。