I have a simple Inventory
class going on, that is in charge of managing player Storage and equipped items, but currently I have single method that operates on player himself called updatePlayer
and I am not sure if it is that good idea, even though it works. So when the player equips armor, for example, this is what happens in the 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;
}
}
And this is how I handle the stat change to the real player instance inside the main method:
Inventory inv = new Inventory(currentPlayer);
inv.equipArmor();
currentPlayer = inv.updatePlayer();
currentPlayer.setInventory(inv.updateInventory());
Is this system okay, or should I try to refactor to something else?
A good thing to ask yourself is "does this model in the real world?". If you are going to use composition, you may ask yourself the question, "does an Inventory
have a Player
?".
The answer here is no, A Player
is much more likely to have an Inventory
, so following that logic you can say:
class Player {
Inventory inventory;
void equipArmor(Armor armor) {
inventory.addArmor(armor);
}
}
class Inventory {
Armor armor;
void addArmor(Armor armor) {
this.armor = armor;
}
}
And this is how you would use it:
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);
}
Note that most of this is made up, but I used it to demonstrate an OO concept