Video in progress

What is the Command pattern and where is it used?

Command turns a request into an object: "what to do" is gathered into one class. That makes it easy to queue an action, run it later, log it or undo it.

📖 Answer

A plain method call runs immediately and vanishes without a trace. Command turns it into something you can keep.

public interface Command {
    void execute();
}

record SendEmail(String to, String subject) implements Command {
    public void execute() { /* SMTP */ }
}

record ResizeImage(Path file, int width) implements Command {
    public void execute() { /* ImageIO */ }
}

ExecutorService pool = Executors.newFixedThreadPool(4);
List<Command> jobs = List.of(new SendEmail("a@b.uz", "Salom"), new ResizeImage(path, 800));
jobs.forEach(cmd -> pool.submit(cmd::execute));

In Java, Runnable and Callable are really the simplest Commands. ExecutorService decides when and on which thread to run them, and the caller doesn't know.

Other places: undo/redo in a text editor, GUI buttons, job queues, commands in CQRS.