可能无用的对象

时间:2016-04-08 12:56:53

标签: java oop

在我撰写Generic RPG Number 3,742时,我为ItemsInventory实施了一个课程。从概念上讲,Item是一个特定的项目。我想要一种'堆叠'项目的方法,这样我Inventory中每种Item只能有一个条目。

为此,我创建了Item Wrapper private ItemNumber of Items。它还有一些方法来处理所有这些Items等的总重量。

当我对此进行扩展时遇到了麻烦。我发现自己想在我的Item课程中复制几乎所有Item Wrapper方法。另一种方法是制作Item public并在Inventory类中引用它,感觉同样糟糕。

这是Item Wrapper不应该存在的标志吗?这会导致Inventory中的重复项或Item的概念出现问题。我觉得可能有更好的解决方案,但我似乎无法找到它。

编辑:为当前的课程结构添加更多说明。

Player_Character有一个私人Inventory

InventoryVector的私人[mumble] Item Wrapper

Item Wrapper有一个私人Item和私有int“how_many”。

注意'有'。由于我一直在Inventory进行扩展,因此我注意到我一直需要Item_Name或其他特定于Item的内容。如果我不更改我的设计,我会将Get中的所有Item函数复制到Item Wrapper或将Item公开(在Item Wrapper中)。

3 个答案:

答案 0 :(得分:5)

您的ItemWrapper类型听起来可能是composite的一个示例,这是一种非常常见的设计模式。如果是这样,我不会认为它是多余的或无用的。

答案 1 :(得分:4)

我认为你使问题变得比它需要的更复杂。您可以通过向quantity添加Item字段并提供使用quantityweight计算总权重的方法来简化问题。您的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 ...

没有问题