gpt4 book ai didi

java - 我不想在 java 中使用 "instanceof",我该怎么办?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:24:02 24 4
gpt4 key购买 nike

我有两个抽象类,名为 RobotGeometricElement。他们每个人都有子类。我需要构建一个包含 RobotGeometricElement 的 NxM 矩阵,所以我写了另一个类并将其命名为 Item,然后是 RobotGeometricElement从那个类继承。

代码如下:

public class Item {
private Dot currentLocation;
private boolean taken;

public Item(Dot location) {
int x = location.getXcomponent();
int y = location.getYcomponent();
currentLocation = new Dot(x,y);
taken = false;
}

// more code
}

public abstract class GeometricElement extends Item {

private float area;

public GeometricElement(Dot location) {
super(location);
}
}


public abstract class Robot extends Item {
private float basketArea;

/* Constructor */

public Robot(Dot location, float basketNewArea) {
super(location);
basketArea = basketNewArea;
}

// some more code
}

负责存储 Item 的类称为 Ground:

public class Ground {

private Item[][] board;
private Queue elementQueue;

/* Constructor */

public Ground(int row,int col) {
board = new Item[row][col];
this.elementQueue = new Queue();
}

// more code

public void addElementsToRobot() {
while (this.elementQueue.doesQueueHasItems()) {
GeometricElement element = elementQueue.popElementFromQuque();
int x = element.getXlocation();
int y = element.getYlocation();
if (this.board[x][y].isTaken()) {
if (board[x][y] instanceof Robot) {
// add geometric element to the basket
}
}
}
}
}

如上所述,我需要在棋盘中存储一个Robot 或一个GeometricElement。当我尝试从矩阵('Ground' 中的'board' 矩阵)读取时,问题就开始了:我似乎无法找到一种方法来判断单元格中是否有机器人或 GeometricElement,而不使用 实例

最佳答案

我当然不知道你的目标,但从我的脑海中可以看出:

我个人会使用 Composite 模式重构它,以便您可以以统一的方式访问所有元素。至于没有实例的确定,你可以在你的 Item 类上有一个抽象方法来区分彼此。或者你可以让公共(public)属性(property)这样做。或者您可以提供更好的设计。

这实际上取决于您要实现的目标。 Instanceof 实际上可能是您问题的解决方案,但通常它指向更深层次的设计问题。

关于java - 我不想在 java 中使用 "instanceof",我该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8457153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com