Reputation: 1167
I'm pretty new to Java, as the nature of my post will give away
I need to create a class which contains a set of methods which can easily be extended by a programmer, should it be needed. I thought about having two classes: Commands
and Command
. Commands
contains an array of Command
objects, and is where the programmer can add new commands. The Command
class has two fields. The name of the class, and a method signature. I'm not sure how this can be done. In C, I think you can have a struct of functions, so can we have a class where the instances of the class are methods? Or am I completely on the wrong track?
I thought about trying to do something like this:
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;
}
}
I know there are a lot of things wrong with this, but I'm stuck on finding the right way. Hints/help would be fantastic.
Upvotes: 1
Views: 165
Reputation: 11662
Java does not have function pointers. This is a common trick:
abstract class (or interface) Command {
void execute();
}
public void createCommands() {
commands.add(new Command(){
@Override
void execute() {
something.move();
}
});
}
Upvotes: 3
Reputation: 46480
Note that you can't directly pass methods about in Java. Instead, they will need to be objects that implement a common interface. For example, your methods could become objects that implement the Runnable interface. Then you just call "run" when you need to use the method.
Upvotes: 1
Reputation: 6229
Java doesn't have function pointers, so this doesn't work. What you probably want to do is have a Command interface with an execute()
method that you implement in concrete subclasses.
It's a matter of style, but I usually wouldn't have a name field in the Command implementations. Rather, I would just create a Map<String, Command>
that holds the name for each Command.
Upvotes: 1
Reputation: 13564
I think you want to use the 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
The Wikipedia page has an example.
Your Command
should be an interface with an execute
method. A programmer can code a class that implements the Command
interface, and thus she/he must implement the execute
method to do what is needed. You can then have a Command[]
array, and for each Command
object you can simply call execute
to perform the task.
Upvotes: 5