我正在创建一个游戏。游戏具有GameMap。为了在GameMap上跟踪事物的状态,我想为每个事物创建ArrayLists。问题是,我不想创建用于添加或删除每种ArrayList类型的项目的单独方法。我是新手,所以我首先想到的就是“instanceof”运算符。

请记住,目前,GameMap是一个离散类,而不是接口(interface)或抽象类。目的是在初始化游戏时实例化GameMap对象。

public class GameMap {

//GameMap has a name
private String mapName;

//GameMap has rooms
private ArrayList<Room> roomsOnMap;

//GameMap has items
private ArrayList<Item> itemsOnMap;

//GameMap has people
private ArrayList<Person> peopleOnMap;

//construct GameMap with rooms, items, and people
private GameMap(String mapName, ArrayList someRooms, ArrayList someItems, ArrayList somePeople)
{
    this.mapName = mapName;
    this.roomsOnMap = someRooms;
    this.itemsOnMap = someItems;
    this.peopleOnMap = somePeople;
}

public void addObject(Object o)
{
    //HOW DO I AVOID THIS?
    if(o instanceof Room)
    {
        roomsOnMap.add((Room) o);
    }
    else if(o instanceof Item)
    {
        itemsOnMap.add((Item) o);
    }
    else if(o instanceof Person)
    {
        peopleOnMap.add((Person) o);
    }
}

最佳答案

使用overloaded方法:

void addObject(Room room) {
  roomsOnMap.add(room);
}

void addObject(Item item) {
  itemsOnMap.add(item);
}

..

09-08 06:49