Java - 创建一个方法数组 [英] Java - Creating an array of methods
问题描述
我正在为学校的进步设计一个基于文本的冒险游戏.我将每个级别"设置为一个类,并将每个可探索区域(节点)设置为相应类中的一个方法.
I'm designing a text-based adventure game for a school progress. I have each "level" set up as a class, and each explorable area (node) as a method within the appropriate class.
困扰我的是从一个节点移动到另一个节点的代码.因为每个节点最多连接到四个其他节点,所以我必须在每个方法中重复一段极其相似的代码块.
What's messing with me is the code to move from one node to another. Because each node is connected to up to four other nodes, I have to repeat an extremely similar block of code in each method.
我更喜欢在每个节点的开头包含一组方法,如下所示:
What I'd prefer to do is include an array of methods at the beginning of each node, like this:
public static void zero()
{
... adjacentNodes[] = {one(), two(), three(), four()};
}
然后将该数组发送到通用方法,并让它将播放器发送到正确的节点:
And then send that array to a generic method, and have it send the player to the right node:
public static void move(...[] adjacentNodes, int index)
{
adjacentNodes[index];
}
我简化了我的代码,但这是总体思路.这可能吗?
I simplified my code, but that's the general idea. Is this possible?
推荐答案
每当您想到函数指针时,您都会使用适配器模式(或变体)转换为 Java.应该是这样的:
Whenever you think of pointer-to-function, you translate to Java by using the Adapter pattern (or a variation). It would be something like this:
public class Node {
...
public void goNorth() { ... }
public void goSouth() { ... }
public void goEast() { ... }
public void goWest() { ... }
interface MoveAction {
void move();
}
private MoveAction[] moveActions = new MoveAction[] {
new MoveAction() { public void move() { goNorth(); } },
new MoveAction() { public void move() { goSouth(); } },
new MoveAction() { public void move() { goEast(); } },
new MoveAction() { public void move() { goWest(); } },
};
public void move(int index) {
moveActions[index].move();
}
}
这篇关于Java - 创建一个方法数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!