【发布时间】:2020-09-04 11:50:52
【问题描述】:
我很确定我可以在 Stackoverflow 上找到这个问题的答案。不幸的是,我不知道这样做的具体公式。
鉴于以下代码我有问题,我想避免类型检查。 cmets 可能会比我的话更好地描述它。
现在我正在尝试创建一个形状系统,其中每个形状都可以与每个可能的特定形状发生碰撞。 碰撞类:
public class ShapeCollision {
public static boolean intersects(RectShape rectShape1, RectShape rectShape2) { return true; }
public static boolean intersects(LineShape lineShape, RectShape rectShape) { return true; }
public static boolean intersects(RectShape rectShape1, Shape shape) { return true; }
public static boolean intersects(LineShape lineShape, Shape shape) { return true; }
public static boolean intersects(Shape shape1, Shape shape2){ return true; }
}
形状类:
public class RectShape extends Shape {
Vector size;
public RectShape(Vector pos, Vector size) {
super(pos);
this.size = size;
}
@Override
public boolean intersects(IShape shape) {
return ShapeCollision.intersects(this, shape);
}
}
public class LineShape extends Shape {
Vector pos2;
public LineShape(Vector pos, Vector pos2) {
super(pos);
this.pos2 = pos2;
}
@Override
public boolean intersects(IShape shape) {
return ShapeCollision.intersects(this, shape);
}
}
public class Shape implements IShape {
protected Vector pos;
public Shape(Vector pos) {
this.pos = pos;
}
@Override
public Vector getPos() {
return pos;
}
@Override
public void setPos(Vector pos) {
this.pos = pos;
}
@Override
public void move(Vector movementAmount) {
pos.add(movementAmount);
}
@Override
public boolean intersects(IShape shape) {
return ShapeCollision.intersects(this, shape);
}
}
这对我来说是令人困惑的部分:
Shape rect = new RectShape(new Vector(0,0), new Vector(20,20));
Shape rect2 = new RectShape(new Vector(0,0), new Vector(20,20));
Shape line = new LineShape(new Vector(0,0), new Vector(20,20));
//Since I am saving shape and no specific shapetype, it will pass shape and pick the specific superFunction
//Right now it calls the intersects(RectShape rectShape1, Shape shape) function due to calling it through the shape variable
rect.intersects(rect2);
//This calls the intersects(LineShape lineShape, Shape shape) function
rect.intersects(line);
//This calls the intersects(Shape shape1, Shape shape2) function
ShapeCollision.intersects(rect, line);
如何在不指定变量类型的情况下实现它,即调用带有子类参数的“正确”函数。 (例如:(LineShape lineShape,RectShape rectShape))
我不想在这些函数中进行任何类型检查并专门调用这些函数,而是尽可能使用一些 DesignPatters 或类似的东西:)
【问题讨论】:
-
如果我没记错的话 Shape 类实现了 IShape 和所有其他类 LineSHape 和 RactShape 扩展了 Shape 类。正确吗?
-
@GauravJeswani 你是对的。您还可以就我应该使用的类结构提出建议。我只是好奇这是否可能。
-
如果是这样的话 ShapeCollision.intersects(this, shape);正在编译?
-
为了回答你的问题,我会调整代码,让一切都可见。我不确定你在问什么。我想你可能误解了一些东西;)
-
是的,请更新代码。
标签: java polymorphism subclass