In event-driven systems, the Command pattern's main advantage is turning actions into first-class objects, which decouples what triggers an event from what handles it. That separation is exactly what event-driven architectures need to stay flexible and extensible.
A UI event dispatcher can map button clicks to Command objects like SaveCommand or DeleteCommand, so adding a new button only requires a new command class, not changes to the dispatch logic.
import java.util.HashMap;
import java.util.Map;
public class EventCommandDispatcher {
interface Command { void execute(String payload); }
static class SaveCommand implements Command {
public void execute(String p) { System.out.println("Saved " + p); }
}
static class DeleteCommand implements Command {
public void execute(String p) { System.out.println("Deleted " + p); }
}
// The dispatcher never changes when new buttons/events are added
static class Dispatcher {
private final Map<String, Command> commands = new HashMap<>();
void register(String event, Command c) { commands.put(event, c); }
void dispatch(String event, String payload) {
Command c = commands.get(event);
if (c == null) System.out.println("No command for " + event);
else c.execute(payload);
}
}
public static void main(String[] args) {
Dispatcher dispatcher = new Dispatcher();
dispatcher.register("save-clicked", new SaveCommand());
dispatcher.register("delete-clicked", new DeleteCommand());
dispatcher.register("export-clicked", p -> System.out.println("Exported " + p + " as PDF"));
dispatcher.dispatch("save-clicked", "invoice-42");
dispatcher.dispatch("export-clicked", "invoice-42");
dispatcher.dispatch("print-clicked", "invoice-42");
}
}Saved invoice-42
Exported invoice-42 as PDF
No command for print-clicked
A concise interview answer is
Command decouples the event source from the handler by wrapping each action as an object, which lets an event-driven system queue, log, or undo actions instead of executing them inline and immediately. It also means new event types are just new command classes, with no changes needed to the dispatcher itself.
Last updated: 1 November 2026
Previous question: In what situations would you use the Command pattern, such as in undo/redo operations?
Next question: How does the Command pattern decouple the sender and receiver of a request?