Java – create an array of methods

I'm designing a text - based adventure game for school progress I set each "level" as a class and each explorable area (node) as a method in the appropriate class

What's confusing is the code that moves from one node to another Because each node is connected to up to four other nodes, I have to repeat a very similar block of code in each method

What I like to do is to include a series of methods at the beginning of each node, as shown below:

public static void zero()
{
    ... adjacentNodes[] = {one(),two(),three(),four()};
}

Then send the array to the generic method and send it to the correct node:

public static void move(...[] adjacentNodes,int index)
{
    adjacentNodes[index];
}

I simplified my code, but that's a general idea Is that possible?

Solution

Whenever you think of pointer to function, you can convert to Java by using adapter mode (or variant) This will be:

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[i].move();
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>