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?
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With