Java多态 - 如何在不同的类中调用相同的方法 [英] Java polymorphism - how to call same method in different classes
问题描述
所以我在java中制作一个游戏,我有两个方法的对象; update()
和 render()
。
So I'm making a game in java, and I have objects all with the 2 methods; update()
and render()
.
在我的主类中,游戏循环所在的位置,我必须同时调用 update()
和 render()
每个可更新和可渲染的对象的方法。
有没有办法设置某种形式的接口我可以调用方法一次它会在所有实现的对象中调用它吗?
In my main class, where the game loop resides, I have to call both the update()
and render()
methods for every object that is updatable and renderable.
Is there any way to set up some form of interface where I can call the methods once and it will call it in all implemented objects?
推荐答案
其他答案是正确的,但是使用它会更好复合模式:
The other answers are correct, however it would be much better to use the composite pattern:
public interface GameComponent {
void render();
void update();
}
public abstract class ChildComponent implements GameComponent {
protected ContainerComponent parent; // (see below)
// getter and setter for parent
}
public class ContainerComponent implements GameComponent {
protected List<GameComponent> children = new ArrayList<>();
public void add(GameComponent child) {
this.children.add(child);
child.setParent(this);
}
@Override
public void update() {
for (GameComponent c : this.children) {
c.update();
}
}
@Override
public void render() {
for (GameComponent c : this.children) {
c.render();
}
}
}
然后你实现您的特定 GameComponent
s,以便它们扩展 ChildComponent
或 ContainerCompoenent
:
Then you implement your specific GameComponent
s so that they extend either ChildComponent
or ContainerCompoenent
:
public class Player extends ChildComponent {
@Override
public void update() {
// update player
}
@Override
public void render() {
// render player
}
}
public class World extends ContainerComponent {
@Override
public void update() {
super.update(); // update world's children (the player)
// update the world (this can be done either after or before updating children,
// you choose how to update your world)
}
@Override
public void render() {
super.render(); // render world's children (the player)
// render the world (this can be done either after or before rendering children,
// you choose how to render your world)
}
}
然后,在你的主循环中:
Then, in your main loop:
// Create player and world
Player p = new Player();
World w = new World();
// Add player to world
w.add(p);
// Update everything
w.update();
// Render everything
w.render();
这样,您创建复合 GameComponent
s,然后你 update()
和 render()
只是最顶层的 - level ContainerComponent
。
This way, you create a composite of GameComponent
s, and then you update()
and render()
just the topmost-level ContainerComponent
.
这篇关于Java多态 - 如何在不同的类中调用相同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!