Files
design-patterns/03-behavioral/command/README.md

33 lines
1.4 KiB
Markdown

# Command Design Pattern — Java Example
**Pattern:** Behavioral → Command
**Article:** https://ankurm.com/command-design-pattern-java/
## What this example shows
A text editor with full undo support. `Command` declares `execute()`/`undo()`/`getDescription()`. `InsertCommand` and `DeleteCommand` are concrete commands that call back into the receiver, `TextEditor`. `DeleteCommand` captures the text it's about to delete *before* deleting it, so `undo()` can restore it. `CommandHistory` is the invoker: it pushes executed commands onto a stack and pops/undoes them on request, without knowing what any command actually does.
## How to run
```bash
javac command/*.java -d out/command
java -cp out/command command.Main
```
Requires Java 25.
## Post Section ↔ File Mapping
| Post Section | File(s) |
|---|---|
| Step 1 — Command Interface | `Command.java` |
| Step 2 — The Receiver (TextEditor) | `TextEditor.java` |
| Step 3 — Concrete Commands | `InsertCommand.java`, `DeleteCommand.java` |
| Step 4 — The Invoker (CommandHistory) | `CommandHistory.java` |
| Demo | `Main.java` |
Note: the `MacroCommand` snippet (Composite applied to Command) and the `Runnable`/`Callable`/`CompletableFuture` JDK snippets are illustrative only — they are not part of this repository's runnable example.
Article: https://ankurm.com/command-design-pattern-java/
All patterns: https://ankurm.com/design-patterns-java/