如何执行依赖于对象的方法?

时间:2013-04-01 16:56:28

标签: java oop

我的Canvas有几个Shape个对象。这些对象是可选择的,并在lastSelectioncurrentSelection中进行跟踪。

在转移+点击时,我想通过一行连接一些Shapes。但对于每个Shape实现,连接的方式应该不同。

如何重写以下内容并删除1)instanceof检查,2)类型转换?

class Shape;
class Ellipse extends Shape;
class Line extends Shape;
class Square extends Shape;
//some more

Shape lastSelection;
Shape currentSelection;

onClick() {
    if (lastSelection instanceof Ellipse && currentSelection instanceof Ellipse) {
        connect((Ellipse) lastSelection, (Ellipse) currentSelection);
    }
    if (lastSelection instanceof Square && currentSelection instanceof Square) {
        connect((Square) lastSelection, (Square) currentSelection);
    }
    //some more
}


connect(Ellipse e1, Ellipse 2) {}
connect(Square s1, Square s2) {}

0 个答案:

没有答案