Creating a player that can hold different items

I am making a game using Java, LibGDX and Box2D. What would be the best way to create a player that can hold:

• no item
• one item from group A
• one item from group B
• one item from both groups

Items from group A can only be used to attack, and are held in the right hand.
Items from group B can only be used to defend, and are held in the left hand.

Should I add the item to the player class and render/update the item in the player class? Or is there any best way to this that I am not aware?

This is the best way I know how to do it:

I would also be interested in any design pattern that could be applied to this situation.

• Are there any programmatic differences between A & B type items? Can the player attack with a shield or defend with a gun? – Pikalek Dec 26 '16 at 3:06
• @Pikalek Yes there are. Itens from type A can only be used to attack and they are positioned on the right hand of the player. Itens from type B can only be used to defend and they are positioned on the left hand of the player. – Daniel Oliveira Dec 26 '16 at 3:48

I'd say, don't sweat it. Your character's two hands are independent of one another, the two items groups have distinct interfaces and are meant to be used in different ways. Just use a properly-typed reference for each hand, there's no need for type erasure or fancy design patterns.

public class Player {

private DefenceItem leftHandItem;
private AttackItem  rightHandItem;

// ...

public void update() {
// Update yourself

if(leftHandItem != null)
leftHandItem.update();

if(rightHandItem!= null)
rightHandItem.update();
}

public void draw() {
// Draw yourself

if(leftHandItem != null)
leftHandItem.draw();

if(rightHandItem!= null)
rightHandItem.draw();
}

public void attack() {
if(rightHandItem!= null)
rightHandItem.attack();
}

public void defend() {
if(leftHandItem != null)
leftHandItem.defend();
}
}


I've kept these simple void() methods for the example, but passing the required information around won't be problematic since all type information is preserved.

• You should only call the methods if there is an item in that hand – Bálint Dec 26 '16 at 16:47