How to avoid code duplication when defining many objects with various characteristics?
I think this must be a very common problem in game programming where you have lots of characters with various capabilities.
I am using protocols to define actions for characters wherever feasible and inheritance when I need objects to share large blocks of code. The problem with protocols is that they only define the interface, so implementation i开发者_Python百科s often duplicate code. Is there a better approach to this problem, or in this case is it acceptable to have some code duplication? There's no multiple inheritance in Objective-C, so that's out of the question.
This is a common problem with inheritance in game design. You can try using components instead. There are different ways to implement a component based system, but generally a game entity is a container of components and you can easily reuse components for different entities. Here are some more resources you might find useful:
- Evolve your hierarchy
- Game object structure : inheritance vs. aggregation
- Powerpoint presentation from GDC Canada
- Component based entity system design
"I think this must be a very common problem in game programming where you have lots of characters with various capabilities."
No, generally not. It sounds like you're creating new classes or types for each variety of character in the game, whereas normally we just create a Character class and implement the different behaviour via different methods, or interchangeable behaviour classes. If there is wildly differing behaviour then it's common to put those in scripts written in a different language. The many permutations of differing capabilities is essentially a data problem, not a code problem.
精彩评论