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

标签 java class object methods field

我是 Java 的新手,因为我的帖子的性质会泄露

我需要创建一个包含一组方法的类,如果需要,这些方法可以很容易地由程序员扩展。我想过有两个类:CommandsCommandCommands 包含一组 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;
    }
}

我知道这有很多问题,但我一直在寻找正确的方法。提示/帮助会很棒。

最佳答案

我想你想使用 Command pattern :

In object-oriented programming, the command pattern is a design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time

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

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

关于java - 有一个 Java 类,其中一个字段是一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5755132/

相关文章:

java - 使用 JDBC 将用户定义的表类型传递给 SQL Server 存储过程

java - 启动应用程序时后台服务杀死我的应用程序

类方法中的 Python 关键字参数

php - 使用主题标签获取对象属性

javascript - 使用 lodash 将对象转换为数组

java - 使用 Javadoc 和 Ant 测量文档覆盖率

java - 如何知道所需的核心数和内存数?

class - 什么是 uml 刻板印象以及如何使用它

java 调用另一个类的方法从同一个包中打印

javascript - 数组内部的对象——在一个范围内有效,但在另一个范围内无效?