我是 Java 的新手,因为我的帖子的性质会泄露
我需要创建一个包含一组方法的类,如果需要,这些方法可以很容易地由程序员扩展。我想过有两个类:Commands
和 Command
。 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;
}
}
我知道这有很多问题,但我一直在寻找正确的方法。提示/帮助会很棒。
最佳答案
我想你想使用 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/