在我撰写Generic RPG Number 3,742
时,我为Items
和Inventory
实施了一个课程。从概念上讲,Item
是一个特定的项目。我想要一种'堆叠'项目的方法,这样我Inventory
中每种Item
只能有一个条目。
为此,我创建了Item Wrapper
private
Item
和Number of Items
。它还有一些方法来处理所有这些Items
等的总重量。
当我对此进行扩展时遇到了麻烦。我发现自己想在我的Item
课程中复制几乎所有Item Wrapper
方法。另一种方法是制作Item
public
并在Inventory
类中引用它,感觉同样糟糕。
这是Item Wrapper
不应该存在的标志吗?这会导致Inventory
中的重复项或Item
的概念出现问题。我觉得可能有更好的解决方案,但我似乎无法找到它。
编辑:为当前的课程结构添加更多说明。
Player_Character
有一个私人Inventory
。
Inventory
有Vector
的私人[mumble] Item Wrapper
。
Item Wrapper
有一个私人Item
和私有int
“how_many”。
注意'有'。由于我一直在Inventory
进行扩展,因此我注意到我一直需要Item_Name
或其他特定于Item
的内容。如果我不更改我的设计,我会将Get
中的所有Item
函数复制到Item Wrapper
或将Item
公开(在Item Wrapper
中)。
答案 0 :(得分:5)
您的ItemWrapper
类型听起来可能是composite的一个示例,这是一种非常常见的设计模式。如果是这样,我不会认为它是多余的或无用的。
答案 1 :(得分:4)
我认为你使问题变得比它需要的更复杂。您可以通过向quantity
添加Item
字段并提供使用quantity
和weight
计算总权重的方法来简化问题。您的ItemWrapper
并未添加其他字段和方法无法执行的任何操作。
答案 2 :(得分:1)
你所描述的内容对我来说是尖叫,因为Map
做得非常好。为什么没有Inventory
实现类似以下内容;
public class Inventory {
private static final int MAX_SIZE = 10;
private final Map<Type, List<Item>> inventoryItems = new HashMap<Type, List<Item>>();
// Keep track of the total number of items in the inventory
private int totalSize;
public void add(Item item) {
// If the total size is greater than the max then don't allow the operation...
if(totalSize == MAX_SIZE){
throw new IllegalStateException("Exceeded maximum size");
}
if (!inventoryItems.containsKey(item.getType())) {
inventoryItems.put(item.getType(), new ArrayList<Item>());
}
inventoryItems.get(item.getType()).add(item);
totalSize++;
}
public List<Item> getItems(Type type) {
return inventoryItems.get(type);
}
public int getTotalWeight() {
int total = 0;
for (List<Item> items : inventoryItems.values()) {
total += calculateTotalWeight(items);
}
return total;
}
public int getTotalWeightByType(Type type) {
return calculateTotalWeight(inventoryItems.get(type));
}
private int calculateTotalWeight(List<Item> items) {
int total = 0;
for (Item item : items) {
total += item.getWeight();
}
return total;
}
public void remove(Item item) {
// Remove the item from inventoryItems and decrement the count
totalSize--;
}
}
删除了对ItemWrapper
课程的需求。
然后你会有一个Character
类,它可以看起来像......
public class Character {
private final String name;
... // Any other fields
private final Inventory inventory;
public Character(String name) {
this.name = name;
this.inventory = new Inventory();
}
...
public void addToInventory(Item item) {
inventory.add(item);
}
public List<Item> getItemsByType(Type type) {
return inventory.getItems(type);
}
public void removeFromInventory(Item item) {
inventory.remove(item);
}
...
}
注意:强>
你提到你正在使用Vector
,它在每次操作时都有同步的开销(可能是不必要的)。我真的认为使用Map
...