From 8f56ac2854be4c38c9cd98696e4052763348ad65 Mon Sep 17 00:00:00 2001 From: Ankur Date: Wed, 24 Jun 2026 15:40:36 +0530 Subject: [PATCH] Flyweight: sync post code blocks to repo exactly, Java 25, add H6 file labels and README mapping --- 02-structural/flyweight/README.md | 31 +++++++++++++++++++++++++++++++ README.md | 17 +++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 02-structural/flyweight/README.md diff --git a/02-structural/flyweight/README.md b/02-structural/flyweight/README.md new file mode 100644 index 0000000..5696845 --- /dev/null +++ b/02-structural/flyweight/README.md @@ -0,0 +1,31 @@ +# Flyweight Design Pattern — Java Example + +**Pattern:** Structural → Flyweight +**Article:** https://ankurm.com/flyweight-design-pattern-java/ + +## What this example shows + +A forest of 1,000 trees shares just 3 `TreeType` flyweight objects (one per species) instead of allocating a new heavy object per tree. `TreeType` holds the intrinsic (shared) state — name, color, texture. `Tree` holds only the extrinsic (unique) state — x/y position — plus a reference to its shared `TreeType`. `TreeFactory` is the pool manager: `Map.computeIfAbsent()` returns an existing flyweight or creates and caches one. + +## How to run + +```bash +javac flyweight/*.java -d out/flyweight +java -cp out/flyweight flyweight.Main +``` + +Requires Java 25. + +## Post Section ↔ File Mapping + +| Post Section | File(s) | +|---|---| +| Step 1 — The Flyweight (TreeType) | `TreeType.java` | +| Step 2 — The Factory (TreeFactory) | `TreeFactory.java` | +| Step 3 — The Context (Tree) | `Tree.java` | +| Putting the Forest Together | `Main.java` | + +Note: the "Flyweight in the JDK: String Pool and Integer Cache" and "Measuring the Benefit" snippets are illustrative only — they are not part of this repository's runnable example. + +Article: https://ankurm.com/flyweight-design-pattern-java/ +All patterns: https://ankurm.com/design-patterns-java/ diff --git a/README.md b/README.md index e877130..27952d0 100644 --- a/README.md +++ b/README.md @@ -270,6 +270,23 @@ javac 02-structural/facade/*.java -d out/facade java -cp out/facade facade.Main ``` +### Flyweight (`02-structural/flyweight/`) + +| Post Section | File(s) | +|---|---| +| Step 1 — The Flyweight (TreeType) | `TreeType.java` | +| Step 2 — The Factory (TreeFactory) | `TreeFactory.java` | +| Step 3 — The Context (Tree) | `Tree.java` | +| Putting the Forest Together | `Main.java` | + +Note: the "Flyweight in the JDK: String Pool and Integer Cache" and "Measuring the Benefit" snippets are illustrative only — they are not part of this repository's runnable example. + +Run it: +```bash +javac 02-structural/flyweight/*.java -d out/flyweight +java -cp out/flyweight flyweight.Main +``` + ## Reference - *Design Patterns: Elements of Reusable Object-Oriented Software* — Gamma, Helm, Johnson, Vlissides