简体   繁体   中英

Should I add interfaces for my simple game classes?

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 (eg in an attack).

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

uml 图

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM