Design patterns and domain modeling
Command
Represent a request explicitly. Executed Java 21 fixture.
Formal Syntax & Structure
java syntaxjava
command.execute(counter)Working Example
Example Snippetjava
public class Main { record Add(int amount) { Add { if (amount <= 0) throw new IllegalArgumentException("amount"); } void execute(Counter c) { c.add(amount); } } static class Counter { private int value; void add(int n) { value = Math.addExact(value, n); } int value() { return value; } } public static void main(String[] args) { var counter = new Counter(); var commands = java.util.List.of(new Add(2), new Add(3)); for (Add command : commands) command.execute(counter); System.out.println(counter.value()); }}