有一个Java类,其中一个字段是一个方法?

And*_*rew 1 java methods field class object

我对Java很新,因为我的帖子的性质会放弃

我需要创建一个包含一组方法的类,如果需要,可以由程序员轻松扩展.我想过有两节课:CommandsCommand.Commands包含一个Command对象数组,是程序员可以添加新命令的地方.该Command课程有两个字段.类的名称和方法签名.我不确定如何做到这一点.在C中,我认为你可以有一个函数结构,那么我们可以有一个类,其中类的实例是方法吗?还是我完全走错了路?

我想过尝试做这样的事情:

public class Commands
{
    private ArrayList<Command> commands;

    /**
     * Constructor for objects of class Command
     */
    public Commands()
    {
        createCommands();
    }

    /**
     * This is where a programmer can add new commands
     */
    public void createCommands()
    {
        commands.add(new Command("move", public void move()));
    }

    /**
     * This is where the programmer can define the move command
     */
    public void move()
    {
        ....
    }
}

public class Command
{
    private String command_name;
    private Method command;

    public Command(String command_name, Method command)
    {
        this.command_name = command_name;
        this.command = command;
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道这有很多问题,但我仍然坚持找到正确的方法.提示/帮助太棒了.

Mar*_*coS 5

我想你想使用Command模式:

在面向对象的编程中,命令模式是一种设计模式,其中一个对象用于表示和封装稍后调用方法所需的所有信息.

维基百科页面有一个例子.

Command应该是一个execute方法的接口.程序员可以编写实现Command接口的类,因此她/他必须实现该execute方法来完成所需的操作.然后Command[],您可以拥有一个数组,对于每个Command对象,您只需调用execute即可执行该任务.