如何在 Java 中对多个继承对象进行建模

发布于 2024-10-08 07:56:58 字数 139 浏览 9 评论 0原文

我在编写的一个小型足球经理游戏中遇到了以下问题。 我有人员、球员、教练、经理等课程。 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

岁月染过的梦 2024-10-15 07:56:58

不要将角色塑造为一种人。该人应该有一个角色的集合

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);
  }
 }

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);
  }
 }
猫烠⑼条掵仅有一顆心 2024-10-15 07:56:58

我有一个 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.

GRAY°灰色天空 2024-10-15 07:56:58

这只是一个建议。

当我读到你的问题时,我意识到你的球员可能会在比赛期间“升级”或“降级”。例如,退役球员可能成为“教练”。

第二件事(您已经注意到)是一个人可能既是教练又是经理。

这就是为什么我要在 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:

  • Player
  • Coach
  • Manager
  • etc.
爱人如己 2024-10-15 07:56:58

您可以为此拥有一个枚举类型,

enum Role {
   Player, Coach, Manager, GroundsKeeper
}

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

这样一个人就可以拥有任意数量的角色。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文