GoF pattern • Behavioral
GoFBehavioralJava example
Command solves a specific structural problem in the design.
Encapsulate an action as an object.
Pattern overview
GoF pattern
Encapsulate an action as an object.
Intent
Turn a request into an object so it can be queued, logged, retried, or undone independently from the caller.
Problem
Callers should trigger work without knowing execution details, timing, or receivers.
Solution
Represent the action as a command object with everything needed to execute it.
Fit and tradeoffs
FamilyGoF
CategoryBehavioral
Best used when
- For queues, jobs, menu actions, workflows, and undoable operations.
Tradeoffs
- Introduces extra types for each command.
- Can be over-abstracted for one-off calls.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
interface Command {
void execute();
}
final class SendWelcomeEmail implements Command {
private final EmailService emailService;
private final String address;
SendWelcomeEmail(EmailService emailService, String address) {
this.emailService = emailService;
this.address = address;
}
public void execute() {
emailService.send(address, "Welcome!");
}
}