所以我刚刚开始用 Java 编写游戏,并且正在编写我的游戏对象。现在我已经读到这里了发展你的层次结构 http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/您应该将游戏构建为组合,而不是大的类层次结构。正如上一个链接中的图片所示:
然而,当实际开始实施时,我有一个小问题:在哪里应用这些接口。
假设您有一个名为 Player 的类以及 Moveable 和 Renderable 接口。您是否使用公共接口变量来实现此目的:
class Player {
public Moveable moveable;
public Renderable renderable;
}
class GenericMoveable implements Moveable {
// Function implementations
}
class PlayerRenderable implements Renderable {
// Function implementations
}
或者您是否尝试通过将接口直接应用于对象来做到这一点:
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
}
目前我感觉第二种方法更好。主要原因是我可以创建以下列表:
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
我真的只是想确认我走在正确的轨道上。我非常确定,在 Java 中通过组合为游戏创建游戏对象时,您希望将接口直接应用于相关的游戏对象,然后在需要时使用私有接口,并直接实现其余功能。它是否正确?我所做的事情有哪些积极和消极的方面?
不过,既然我们已经到了这里,那么在用 Java 实现组合游戏对象时我还需要注意什么呢?我应该采取什么不同的做法?感谢您提前回复,我感谢所有帮助。