问题描述
我非常确定我可以在Stackoverflow上找到此问题的答案。不幸的是,我不知道这样做的具体方式。
鉴于以下代码,我有一个问题,我想避免类型检查。这些评论可能比我的话更好地描述它。
现在,我正在尝试建立一个形状系统,其中每个形状都可以与每个可能的特定形状碰撞。 CollisionClass:
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; }
}
ShapeClasses:
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,20));
Shape line = new Lineshape(new Vector(0,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实例传递给函数调用之前对Shape实例进行一些显式转换,就无法实现所需的结果。
您当然可以使用特定的类声明对象引用,但是我想这并没有帮助。