加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何避免instanceof调用?

发布时间:2020-12-15 02:01:30 所属栏目:Java 来源:网络整理
导读:我定义了这个简单的方法: public static boolean isBorder(int x,int y) throws CollisionDetectionException { try { if ( (levelItems[x][y] instanceof StaticGameObject levelItems[x][y].isVisible()) || (levelItems[x-1][y] instanceof StaticGameOb
我定义了这个简单的方法:

public static boolean isBorder(int x,int y) throws CollisionDetectionException {
        try {
            if ( (levelItems[x][y] instanceof StaticGameObject && levelItems[x][y].isVisible()) ||
                (levelItems[x-1][y] instanceof StaticGameObject && levelItems[x-1][y].isVisible()) ||
                (levelItems[x][y+1] instanceof StaticGameObject && levelItems[x][y+1].isVisible()) ||
                (levelItems[x][y-1] instanceof StaticGameObject && levelItems[x][y-1].isVisible()) ||
                (levelItems[x-1][y-1] instanceof StaticGameObject && levelItems[x-1][y-1].isVisible()) ||
                (levelItems[x-1][y+1] instanceof StaticGameObject &&levelItems[x-1][y+1].isVisible()) ||
                (levelItems[x+1][y] instanceof StaticGameObject && levelItems[x+1][y].isVisible()) ||
                (levelItems[x+1][y+1] instanceof StaticGameObject && levelItems[x+1][y+1].isVisible()) ||
                (levelItems[x+1][y-1] instanceof StaticGameObject && levelItems[x+1][y-1].isVisible()) ) {
                return true;
            } else {
                return false;
            } 
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new CollisionDetectionException("Collision couldn't be checked because checking position " + x + "/" + y + " caluclated values below (0/0)");
        }
    }

如你所见,我有一个2维数组.现在我想检查特定位置((x / y) – >方法参数),如果在2维数组的相邻字段中有任何可见的StaticGameObject.

levelItems数组由所谓的GameObject组成. StaticGameObject是GameObject的直接子类.

任何提示如何改进这种方法?

解决方法

向GameObject添加方法

bool isBorderObject() { return false; }

然后在StaticGameObject中覆盖

bool isBorderObject() { return true; }

将测试更改为

(levelItems[x][y].isBorderObject() && levelItems[x][y].isVisible())

此外,if可能是嵌套的

for (int i = x-1; i <= x+1; ++i) {
   for (int j = y-1; j <= y+1; ++j) {
       GameObject item = levelItems[i][j];
       if (item.isBorderObject() && item.isVisible()) 
           return true;
   }
}
return false;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读