0

我有Canvas几个Shape对象。对象是可选择的,并在 和 中进行lastSelection跟踪currentSelection

在 shift+click 上,我想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) {}
4

0 回答 0