I want to implement a Command Pattern in Java without spamming docens of classes and facilitating future extension of functionality as much as possible (ie, ideally I want to just write a new command inside a 'list' of commands and be done when extending functionality).
Sor such a purpose, I thought of enums:
class MyClass{
interface Command{
void execute();
String getId();
}
enum MyCommands implements Command{
aCmd{
void execute(){/*do something*/}
String getId(){return "aCmd";}
}
}
void MyMethod(String s){
for(Command cmd: MyCommands){
if(s.equals(cmd.getId())) cmd.execute();
}
}
}
Notice that if I want to add a new command, it is as simple as writing it inside MyCommands.
In constrast, suppose I created a class for each Command. Upon creation of the class, I would have to instantiate and add it manually somewhere else, which is something prone to error if you forget it and laborious if you have tons of commands.
Now, my solution works fine if I am not using anything but static fields of MyClass in execute(), which is not what I wanted. How can I overcome this without falling in the problems mentioned in the last paragraph?
Aucun commentaire:
Enregistrer un commentaire