像这样更新玩家统计数据是个好主意吗?

Is it good idea to update player stats like this?

我有一个简单的 Inventory class 正在进行,负责管理玩家存储和装备物品,但目前我只有一个方法可以对玩家本身进行操作,称为 updatePlayer 我不确定这是否是个好主意,即使它可行。因此,例如,当玩家装备盔甲时,这就是 Inventory class:

中发生的情况
public class Inventory {
    private Player playerInstance;
    private Inventory playerInventory;
    public Inventory(Player currentPlayer) {
        playerInstance = currentPlayer;
        playerInventory = currentPlayer.getInventory();
    }

    /*This is a snippet of equipArmor method(to actually choose the armor to equip,
      there are other pieces of code too, but I ommited them to keep it short):*/
    public void equipArmor() {
        playerInstance.setArmorValue(armorToEquip.getArmorStat());
        playerInventory.removeItem(amorToEquip.getID());
    }

    /*And this is the method I am talking about,
      it is basically my cleaner after all operations on inventory have been performed:*/
    public Player updatePlayer(){
        return playerInstance;
    }
}

这就是我在 main 方法中处理对真实玩家实例的统计更改的方式:

Inventory inv = new Inventory(currentPlayer);
inv.equipArmor();
currentPlayer = inv.updatePlayer();
currentPlayer.setInventory(inv.updateInventory());

这个系统还好吗,还是我应该尝试重构为其他东西?

问问自己的一件好事是 "does this model in the real world?"。如果你打算使用组合,你可以问自己这个问题,"does an Inventory have a Player?"。

这里的答案是否定的,A Player 更有可能有 Inventory,所以按照这个逻辑你可以说:

class Player {
    Inventory inventory;

    void equipArmor(Armor armor) {
        inventory.addArmor(armor);
    }
}

class Inventory {
    Armor armor;

    void addArmor(Armor armor) {
        this.armor = armor;
    }
}

这就是您的使用方式:

LootChest chest = Game.getLootChest(); // i'm making these up
Armor armor = chest.getArmor();

Player player = Game.getCurrentPlayer();
if (armor != null && player.accepts()) {
    player.equipArmor(armor);
}

请注意,大部分内容都是虚构的,但我用它来演示一个 OO 概念

我认为更好的设计是让玩家知道他的物品栏,而不是让物品栏知道玩家。因为一个玩家有一个物品栏但一个物品栏没有一个玩家。

public class Player  {
    private final Inventory inventory = new Inventory();

    public void updateInventory() {
        // Update the inventory on the screen here (sync to the player).
    }

    /* Other stuff */
}

public class Inventory {
    // Contents and stuff ...

    public void add(/* Any Item */) { ... }

    public void removeArmor(/* Any Item */) { ... }

    /* Other stuff */
}

使用此解决方案,您没有任何依赖循环

+---> Player -----+
|                 |
+--- Inventory <--+

如何使用它:

Player player = ...;
player.equipArmor();
player.getInventory().removeArmor();
player.updateInventory();

您也可以自动更新库存,但我认为您不想那样做(性能)。