jeudi 11 août 2016

Which pattern should I use to run some action based on command name?

Prerequisites:

String command = "x";
Data data = request.get();

interface Action {
    Response process(Data data);
}

class ActionX implements Action {
    public Response process(Data data) {}
}

class Service {
    public execute(Action action) {
        action.process();
    }
}

I dont't understand how to register my actions. The following options are unacceptable:

// bad because too verbose
case "x":
    action = new ActionX();

and

// bad because package name is a constant string      
action = Class.forName("some.package.name.Action" + command.toUpperCase());

I guess I might try to use Java annotations to solve my problem. Something like this:

@Action(command = "x")
class ActionX implements Action {}

// scan whole classpath etc ...

But maybe I just need to use another pattern....

Aucun commentaire:

Enregistrer un commentaire