mardi 6 octobre 2020

Create commands that register themselves

My goal is to create a set of commands defined by a String (including an argument) that can be called. But I don't want to have an "infinite" if/else chain testing for the command.

I might have a command which is identified by "light" and argument "on" which should turn on the light. Or a command called "door" "open" or "door" "close".

I know all associations at compile time, which means I will do not need to add new command associations at run time.

I was thinking on the Command Design Pattern. But using that design pattern the associations are all created at runtime because they can be associated with multiple objects/instances. And here it's not the case because the command will only be invoked in ONE thing.

In the end, I want something like this:

class LightCommand ... {
    String commandName = "light";    

    void execute(String argument) {
        ...
        if (argument == "on") {
            //do_something
        }
        ...
    }
}

class DoorCommand ... {
    String commandName = "door";
    
    void execute(String argument) {
        ...
        if (argument == "open) {
        }
        ...
}

Which can simply be called with executeCommand(String line) and it automatically finds the appropriate class and executes it.

Instead of this:

if (command == "light) {
    if (argument == "on") {
    ...
    else if (...)
} else if (command == "door") {
    if (argument == "open")
}
...

Aucun commentaire:

Enregistrer un commentaire