更新像这样的球员统计数据是个好主意吗?

时间:2015-10-30 19:20:22

标签: java encapsulation updating

我有一个简单的Inventory课程,负责管理玩家存储和配备项目,但目前我有一个单独的方法,对玩家本身进行操作,称为updatePlayer,我不确定如果这是个好主意,即使它有效。因此,当玩家装备护甲时,这就是Inventory类中发生的事情:

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());

这个系统是否正常,还是我应该尝试重构其他内容?

2 个答案:

答案 0 :(得分:0)

问自己一件好事是"在现实世界中做这个模型?"。如果你打算使用作文,你可以问自己一个问题," Inventory有一个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概念

答案 1 :(得分:0)

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

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();

您也可以自动更新广告资源,但我认为您不希望这样做(效果)。