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

example of players, A items & B items

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:

UML diagram

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

  • \$\begingroup\$ Are there any programmatic differences between A & B type items? Can the player attack with a shield or defend with a gun? \$\endgroup\$ – Pikalek Dec 26 '16 at 3:06
  • \$\begingroup\$ @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. \$\endgroup\$ – 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)

        if(rightHandItem!= null)

    public void draw() {
        // Draw yourself

        if(leftHandItem != null)

        if(rightHandItem!= null)

    public void attack() {
        if(rightHandItem!= null)

    public void defend() {
        if(leftHandItem != null)

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.