爪哇 - 创建一组方法, [英] Java - Creating an array of methods

查看:115
本文介绍了爪哇 - 创建一组方法,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计了一所学校正在进行的基于文本的冒险游戏。我有每一个级别设置为一个类,每个探究性区域(节点)作为适当的类中的方法。

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.

什么是与我搞乱是code,从一个节点移动到另一个。因为每个节点被连接到其他最多四个节点,我必须重复code的极其相似的块中的每个方法

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.

我想preFER做的是包括在每个节点的开头方法的一个数组,像这样:

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];
}

我简化我的code,但这是一般的想法。这可能吗?

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[i].move();
    }
}

这篇关于爪哇 - 创建一组方法,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆