我正在创建一个游戏。一个游戏有一个 GameMap。为了跟踪 GameMap 上事物的状态,我想为每个事物创建 ArrayLists。问题是,我不想创建单独的方法来从每种类型的 ArrayList 中添加或删除项目。我是新手,所以我首先想到的当然是“instanceof”运算符。
请记住,目前,GameMap 是一个离散类,而不是接口或抽象类。目的是在游戏初始化时实例化一个 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);
}
}