Browse Java Design Patterns & Enterprise Application Architecture

Implementing Command in Java

Implement Command in Java by separating request intent from invocation timing and receiver details.

On this page

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}

Why It Helps

The caller no longer needs to know:

  • how the work is performed
  • when it will be executed
  • whether the request will be queued or logged first

That makes Command especially useful in systems with asynchronous or auditable workflows.

When It Is Overkill

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.

Revised on Thursday, April 23, 2026