How would you implement the Command pattern in Java?

The Command pattern is implemented by defining a Command interface with an execute() method, wrapping each action in a concrete command class, and having an Invoker call execute() on whichever command it's given, decoupling the requester from the code that performs the action.

Key Points: • A Command interface declares execute(), and often undo() for reversible operations. • Each concrete command holds a reference to a receiver object and calls the appropriate method on it inside execute(). • An Invoker stores and triggers commands without knowing what each command actually does. • Commands can be queued, logged, or stacked to support undo/redo functionality. • This decoupling lets you parameterize objects with actions and support features like macro commands.

Example: A remote control's button (Invoker) is configured with a LightOnCommand object; pressing the button just calls command.execute(), and the LightOnCommand internally calls light.turnOn() on the actual Light receiver, so the remote never needs to know about Light directly.

Code Example:

interface Command {
    void execute();
}

class LightOnCommand implements Command {
    private final Light light;
    LightOnCommand(Light light) { this.light = light; }
    public void execute() { light.turnOn(); }
}

class RemoteControl {
    private Command command;
    void setCommand(Command command) { this.command = command; }
    void pressButton() { command.execute(); }
}

Interview Tip: A concise interview answer is:

"I implement Command by defining a Command interface with execute(), wrapping each action in its own concrete command that delegates to a receiver, and having an Invoker trigger execute() without knowing the action's details — that decoupling is what makes undo, queuing, and logging of operations easy to add later."