如何在 Java 中对多个继承对象进行建模
我在编写的一个小型足球经理游戏中遇到了以下问题。 我有人员、球员、教练、经理等课程。 Person 是其他类的基类。问题是球员也可以是教练和/或经理。通过添加更多角色(例如地面管理员),我会变得越来越复杂 - 那么,如何才能有效地实现这一点呢?难道没有一个模式吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要将角色塑造为一种人。该人应该有一个角色的集合
Don't model the role as a type of person. The Person should have a collection of Roles
我有一个 Role 接口,其实现类将 Person 包装为数据成员。 (AbstractRole 在这里很有意义。)
优先选择组合而不是继承,尤其是在这种情况下。
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.
这只是一个建议。
当我读到你的问题时,我意识到你的球员可能会在比赛期间“升级”或“降级”。例如,退役球员可能成为“教练”。
第二件事(您已经注意到)是一个人可能既是教练又是经理。
这就是为什么我要在 Person 类中创建 Role 集合。
一个角色可能是一个抽象类,它可能有以下子类:
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:
您可以为此拥有一个枚举类型,
这样一个人就可以拥有任意数量的角色。
You can have an enum type for this
This way a person can have any number of roles.