我应该为我的简单游戏类添加接口吗?

发布于 2025-01-13 23:52:55 字数 295 浏览 3 评论 0原文

我正在尝试为一个简单的游戏创建一个 UML 类图。我有三个继承类(NPCPlayerMonster),它们应该彼此交互(例如在攻击中)。

我想知道在我的简单情况下是否应该使用接口。另外我如何扩展我的图表?

uml 图m

I'am trying to create an UML class diagram for a simple game. I've three inheritance classes (NPC, Player, Monster) and they should interact with each other (e.g. in an attack).

I wonder if I should use interfaces in my simple case. Also how can I expand my diagramm?

uml diagramm

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

韶华倾负 2025-01-20 23:52:55

您的类Character专门用于:NPC(非玩家角色)、PlayerMonster,您想知道是否你需要一个接口:

  • 由于Monster似乎是非玩家角色,它可能应该继承自NPC而不是Character
  • 人类玩家确实不是一个角色,但恰好由游戏中的一个角色代表,将Player和相应的Character<的职责分开可能会很有趣/代码>。因此,两者之间有一个简单的关联,而不是继承。一个直接的优势是玩家可以选择喜欢的角色来模仿他/她。
  • 中介可用于管理游戏中所有角色之间的交互。您可以创建一个Colleague 接口,并让不同的类实现该接口。但是,如果您的同事必然都是角色,那么您可以像以前一样依赖超类。

更一般地说,如果您想解耦类,附加接口是一种经​​过验证的方法。如果您要开发一个要在许多不同的游戏中重用的游戏引擎,您应该明确地考虑它们:然后您将拥有一个仅依赖于独立于任何特定游戏的接口的引擎。然后,每个游戏都会选择相关的类来实现接口。但对于你的具体情况,这似乎有点矫枉过正。

话虽这么说,您将面临的主要挑战是您最终将面临难以发展的深层阶级层次结构。这就是为什么游戏行业更喜欢实体组件系统模式,它更喜欢组合而不是继承。但这是一个不同的故事,并且有关于该主题的完整书籍;-)

Your class Character is specialized into: NPC (Non-Player Character), Player and Monster and you wonder if you'd need an interface:

  • As a Monster seems to be a non-player character, it should probably inherit from NPC instead of Character
  • As a human player really is not a character but just happen to be represented by a character in the game, it could be interesting to separate the responsibilities of the Player and the corresponding Character. So you'd have a simple association between the two and not an inheritance. An immediate advantage, is that the player could chose the preferred character to impersonate him/her.
  • A mediator could be used to manage the interaction between the all the characters in the game. You could create a Colleague interface, and let different classes implement this interface. But if your Colleagues are necessarily all Characters, you could just rely on the superclass as you did.

More generally, an additional interface is a proven approach if you want to decouple classes. You should definitively consider them if you'd develop a game engine that is to be reused in a lot of different games: you'd then have an engine that relies only interfaces that are independent of any specific game. Each game would then pick the relevant classes to implement the interfaces. But for your specific case, it seems to be an overkill.

This being said, the main challenge you'll be confronted with is that you'll end up with deep class hierarchies that'll be difficult to evolve. This is why, the game industry prefers the entity-component-system pattern that prefer composition over inheritance. But this is a different story, and there are full books on that topic ;-)

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