3

i've got the following Problem in a little soccer manager game i'm writing. I've got the classes Person, Player, Coach, Manager. Person is the base Class of the other ones. The Problem is that a Player can also be a Coach and/or a Manager. By adding more Roles (e.g. groundkeeper) i'll get more and more complex - so, how can you implement this efficiently? Isn't there a Pattern for that?

1
  • Yes, composition over inheritance. Commented Dec 21, 2010 at 15:39

4 Answers 4

9

Don't model the role as a type of person. The Person should have a collection of Roles

public enum Role {
  PLAYER,
  COACH,
  REF 
}

public class Player {
  private final String name;
  private Collection<Role> roles = new ArrayList<Role>();

  public Player(String name) {
    this.name = name;
  }

  public void addRole(Role role) {
    this.roles.add(role);
  }
 }
Sign up to request clarification or add additional context in comments.

2 Comments

If you're going to use an enum, your collection should probably be an EnumSet<Role>, but if a person may have more than one "coach" role, for example, then the elements of your collection shouldn't be Role but should be something more specific which encapsulates both the role type (Role) and other role-specific information (like the name of the team that the person is coaching, or a reference to it).
A list, rather than a set, allows the multiple same role multiple times. ;)
1

I'd have a Role interface whose implementation classes wrapped a Person as a data member. (AbstractRole makes sense here.)

Prefer composition over inheritance, especially in this case.

Comments

0

This would be only a proposal.

When I read your question I'm getting an idea that your player may be 'promoted' or 'downgraded' during the game. For instance, a retired player may become a 'coach'.

The second thing (which you've already noticed) is the fact that a single person may be both a coach and a manager.

That's why I would create a collection of Role-s in the Person class.

A Role may could be an abstract class and it may have the following subclasses:

  • Player
  • Coach
  • Manager
  • etc.

Comments

0

You can have an enum type for this

enum Role {
   Player, Coach, Manager, GroundsKeeper
}

class Person {
   final Set<Role> roles = EnumSet.noneOf(Role.class);
}

This way a person can have any number of roles.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.