How to model multiple inheritance objects in Java
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开发者_Go百科 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.
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.
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.
精彩评论