java使用enum类方法中类的HashSet
我有以下枚举类字符,以及枚举类项:
public enum Item
{
COOKIE("cookie"), CRISPS("crisps"), DRINK("drink");
private String description;
/**
* Constructor with description and weight.
* Pre-condition: description not null.
*/
private Item(String description)
{
assert description != null : "Item.Item with null description";
this.description = description;
sane();
}
人物:
public enum Character
{
JESS("Jess", 0.5f,Item.SANDWICH), SALLY("Sally",0.5f, Item.CRISPS),
ANDREW("Andrew" ,0.5f,Item.DRINK),
ALEX("Alex",0.5f,null),CookieMonster("CookieMonster",1.0f,null),
CookieGiver("CookieGiver",1.0f,null),Player("Player",0.0f,null);
private String description;
private ArrayList<Item> charItems = new ArrayList<Item>();
private float probability;
/**
* Constructor initialising description,item and probability.
*/
private Character(String desc,float moveProbability,Item items)
{
description= desc;
charItems.add(items);
probability =moveProbability;
}
public void enterRoom(Room r)
{
}
以下是用于创建房间对象的类
public class Room
{
private String description;
private HashMap<Direction, Room> exits; // stores exits of this room.
private Set<Character> chars; // stores the characters that are in this
room.
/**
* Create a room described "description". Initially, it has
* no exits. "description" is something like "a kitchen" or
* "an open court yard".
* @param description The room's description.
* Pre-condition: description is not null.
*/
public Room(String description)
{
assert description != null : "Room.Room has null description";
this.description = description;
exits = new HashMap<Direction, Room>();
chars = new HashSet<Character>();
sane();
}
我如何在enum类中编写一个方法,比如调用时,CookieGiver为房间中的每个角色提供项目COOKIE
我知道我需要使用HashSetchars,但我想不出一个方法来实现它
# 1 楼答案
将getter添加到
Room
以获取文件室中的字符列表向字符枚举添加一个方法,以将项添加到已保留项的列表中
在
enterRoom
方法中,对于文件室中的每个字符,调用addItem
,向其中添加COOKIE注意:如果多次调用,它将添加多个cookie。如果您不想这样做,您必须检查COOKIE是否已经存在或使用一个集合
编辑:
由于您希望上述策略仅适用于
CookieGiver
,因此一种方法是将enterRoom
的默认逻辑设为空,并覆盖CookieGiver
选项2:
您可以创建一个私有嵌套枚举,其中包含调用
enterRoom
时要执行的操作策略。然后每个角色都会有一个策略来对付它注意:按照评论中的建议,有更好的方法可以做到这一点