I keep running into the same problem, and I'm still not sure the best way to solve it.
Scenario: A set of command objects, and a manager to execute the commands.
Command:
The interface that defines the Command contract.
public interface Command {
public String getSignature;
public Results execute(Object stuff);
}
Command implementation:
One or more objects that implement the Command interface.
public class KillCommand implements Command {
public String getSignature() {
return "kill";
}
public Results execute(Object stuff) {
do stuff...return results...
}
}
Manager:
A manager that knows of all the commands, and accepts a signature to run one of the commands.
Bad manager:
public class CommandManager {
private List<Command> commands;
public CommandManager(List<Command> commands) {
this.commands = commands;
}
public Results executeCommand(Object stuff, String signature) {
for (Command command : commands) {
if (command.getSignature().equals(signature)) {
return commmand.execute(stuff);
}
}
}
}
Better Manager:
public class CommandManager {
private Map<String,Command> commands = new HashMap<>();
public CommandManager(List<Command> commands) {
for (Command command : commands) {
this.commands.put(command.getSignature(), command);
}
}
public Results executeCommand(Object stuff, String signature) {
this.commands.get(signature).execute(stuff);
}
}
My question, what is the best way of solving this scenario? Is there a design pattern/industry norm to solve this scenario?
Aucun commentaire:
Enregistrer un commentaire