问题描述
所以我刚开始用Java编写游戏,我正在编写我的游戏对象。现在我已经在。播放器
将委托依赖于 Movement
对象的所有移动操作和它不关心它必须使用的具体类型的 Movement
对象。
So I am just at the beginning of writing a game in Java and I am writing my game objects. Now I have read here in Evolve Your Hierarchy that you should build your games as compositions and not as a big class hierarchy. As this image from the previous link shows:
However, when actually getting down to the implementation I have one small question about where to apply the interfaces.
Lets say you have a class called Player and the interfaces Moveable and Renderable. Do you implement this using public interface variables:
class Player {
public Moveable moveable;
public Renderable renderable;
}
class GenericMoveable implements Moveable {
// Function implementations
}
class PlayerRenderable implements Renderable {
// Function implementations
}
Or do you try and do this by applying the interfaces directly to the object:
class Player implements Moveable, Renderable {
private GenericMoveable genericMoveable;
// Non-direct Implementation of Moveable
void someMoveFunc(double x, double y) {
genericMoveable.someMoveFunc(x, y);
}
// Direct implementation of Renderable
void someRenderableFunction() {
// Player class specific code
}
}
class GenericMoveable implements Moveable {
// Function implementations
}
Now currently I am feeling that the second method is better. The main reason for that is because I can create the following lists:
List<Renderable> renderObjects; // use this to draw all of the objects to the screen
List<Moveable> moveObjects; // use this to move all objects at once
I really just want confirmation that I am on the right track. I am pretty sure that when creating game objects by composition for games in Java you want to apply the interfaces directly to the Game Object in question and then use private interfaces if you need them and direct implementations of those functions for the rest. Is this correct? And what are the positives and negatives of what I am doing?
Though, while we are here, what else do I need to look out for in the implementation of Compositional Game Objects in Java? What should I do differently? Thanks for any responses in advance, I appreciate any and all help.
That's an interesting link. I gather that what you have in mind for your Player
class is what that article calls a component container. For that, applying the interfaces to the class sounds to me like the way to go. It's the only route that will lead you to a pure aggregation structure (where there is no longer a Player
class per se in your system.
By the way, the structure you're proposing is basically an application of the delegation design pattern. A Player
relies delegates to a Movement
object all movement operations and it doesn't care what specific kind of Movement
object it has to work with.
这篇关于如何用Java编写可靠的Pure Aggregation(组合)游戏对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!