我应该为我的简单游戏类添加接口吗?
我正在尝试为一个简单的游戏创建一个 UML 类图。我有三个继承类(NPC
、Player
、Monster
),它们应该彼此交互(例如在攻击中)。
我想知道在我的简单情况下是否应该使用接口。另外我如何扩展我的图表?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的类
Character
专门用于:NPC
(非玩家角色)、Player
和Monster
,您想知道是否你需要一个接口:Monster
似乎是非玩家角色,它可能应该继承自NPC
而不是Character
Player
和相应的Character<的职责分开可能会很有趣/代码>。因此,两者之间有一个简单的关联,而不是继承。一个直接的优势是玩家可以选择喜欢的角色来模仿他/她。
Colleague
接口,并让不同的类实现该接口。但是,如果您的同事
必然都是角色
,那么您可以像以前一样依赖超类。更一般地说,如果您想解耦类,附加接口是一种经过验证的方法。如果您要开发一个要在许多不同的游戏中重用的游戏引擎,您应该明确地考虑它们:然后您将拥有一个仅依赖于独立于任何特定游戏的接口的引擎。然后,每个游戏都会选择相关的类来实现接口。但对于你的具体情况,这似乎有点矫枉过正。
话虽这么说,您将面临的主要挑战是您最终将面临难以发展的深层阶级层次结构。这就是为什么游戏行业更喜欢实体组件系统模式,它更喜欢组合而不是继承。但这是一个不同的故事,并且有关于该主题的完整书籍;-)
Your class
Character
is specialized into:NPC
(Non-Player Character),Player
andMonster
and you wonder if you'd need an interface:Monster
seems to be a non-player character, it should probably inherit fromNPC
instead ofCharacter
Player
and the correspondingCharacter
. 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.Colleague
interface, and let different classes implement this interface. But if yourColleagues
are necessarily allCharacters
, 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 ;-)