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?
4 Answers
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);
}
}
2 Comments
Bobby Eickhoff
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).
Peter Lawrey
A list, rather than a set, allows the multiple same role multiple times. ;)
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.