Define Commands and Handlers
masterA Command is a request that can return a value. Implement the Command<R> interface where R is the return type.
- If a command returns nothing, use the built-in
Voidytype.
A Handler is a class that implements Command.Handler<C, R>, where C is the command type and R is the return type. The handler's return type must match the command's return type.
By default, handlers are resolved using generics. You can also override the matches(C command) method in the handler to implement dynamic selection logic.
// Define a command
class Ping implements Command<String> {
public final String host;
public Ping(String host) { this.host = host; }
}
// Define a handler
class Pong implements Command.Handler<Ping, String> {
@Override
public String handle(Ping command) {
return "Pong from " + command.host;
}
}
// Dynamic handler selection
class LocalhostPong implements Command.Handler<Ping, String> {
@Override
public boolean matches(Ping command) {
return command.host.equals("localhost");
}
}