Behavioral Design Pattern
Command Design Pattern in Java
Encapsulate a request as an object so it can be queued, logged, undone, or parameterized.
In this lesson: Command turns an action and its receiver into an object. An invoker can execute commands without knowing the receiver's implementation.
Overview
Command is useful when its recurring design problem appears in a real application. It keeps the relevant responsibilities organized while allowing surrounding code to depend on clear abstractions.
Implementation
interface Command { void execute(); }
final class Light { void on() { System.out.println("Light on"); } }
final class LightOn implements Command { private final Light light; LightOn(Light light) { this.light = light; } public void execute() { light.on(); } }
Command command = new LightOn(new Light());
List<Command> queue = List.of(command);
queue.forEach(Command::execute);
When should you use it?
Use Command for job queues, undo and redo, transactions, menu actions, scheduled work, and audit logging.
Next step: Continue with the Design Patterns course and explore the next pattern.