From 967d4903230d255787f59c02f52e28123ae7a5c8 Mon Sep 17 00:00:00 2001 From: Ankur Date: Wed, 24 Jun 2026 16:38:35 +0530 Subject: [PATCH] Command: sync post code blocks to repo exactly, Java 25, split merged commands, add H6 file labels and README mapping --- 03-behavioral/command/README.md | 32 ++++++++++++++++++++++++++++++++ README.md | 16 ++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 03-behavioral/command/README.md diff --git a/03-behavioral/command/README.md b/03-behavioral/command/README.md new file mode 100644 index 0000000..6990a20 --- /dev/null +++ b/03-behavioral/command/README.md @@ -0,0 +1,32 @@ +# 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/ diff --git a/README.md b/README.md index 832949d..6e5197a 100644 --- a/README.md +++ b/README.md @@ -322,6 +322,22 @@ javac 03-behavioral/chain-of-responsibility/*.java -d out/chain java -cp out/chain chain.Main ``` +### Command (`03-behavioral/command/`) + +| 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` | + +Run it: +```bash +javac 03-behavioral/command/*.java -d out/command +java -cp out/command command.Main +``` + ## Reference - *Design Patterns: Elements of Reusable Object-Oriented Software* — Gamma, Helm, Johnson, Vlissides