Implement Command in Java by separating request intent from invocation timing and receiver details.
Command: A pattern that encapsulates a request as an object so it can be invoked, stored, queued, retried, or undone separately from the caller.
In Java, a minimal command contract is often enough:
1public interface Command {
2 void execute();
3}
The command binds intent to a receiver:
1public final class SendEmailCommand implements Command {
2 private final Mailer mailer;
3 private final EmailMessage message;
4
5 public SendEmailCommand(Mailer mailer, EmailMessage message) {
6 this.mailer = mailer;
7 this.message = message;
8 }
9
10 @Override
11 public void execute() {
12 mailer.send(message);
13 }
14}
The caller no longer needs to know:
That makes Command especially useful in systems with asynchronous or auditable workflows.
If the request is never stored, retried, queued, scheduled, logged, or undone, a direct method call may be clearer. Command pays off when the request has a lifecycle of its own.