The Command pattern decouples a request's sender from its receiver by wrapping the action, its parameters, and the receiver reference inside a standalone command object. The sender only depends on a generic Command interface, never on the receiver's concrete class or method.
Key Points: • A Command interface typically exposes a single execute() method. • Each concrete command stores a reference to the receiver and calls the appropriate method on it inside execute(). • The invoker (sender) holds a Command reference and calls execute() without knowing what it actually does. • This separation makes commands easy to queue, log, delay, or undo, since they're just objects. • New commands can be added without changing the invoker's code, following the open/closed principle.
Example: A remote control button (invoker) can hold a LightOnCommand object; pressing the button just calls command.execute(), which internally calls light.turnOn(), so the remote never references the Light class directly.
Code Example:
interface Command {
void execute();
}
class LightOnCommand implements Command {
private Light light;
LightOnCommand(Light light) { this.light = light; }
public void execute() { light.turnOn(); }
}
class RemoteControl {
private Command command;
public void setCommand(Command command) { this.command = command; }
public void pressButton() { command.execute(); }
}Interview Tip: A concise interview answer is:
"Command wraps a request, its parameters, and the receiver into a single object with an execute() method, so the sender only ever depends on the Command interface, not on the receiver's concrete class. That decoupling is what makes it easy to queue, log, or undo commands later without touching the sender's code."