我有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) {}