Flyweight: sync post code blocks to repo exactly, Java 25, add H6 file labels and README mapping

This commit is contained in:
2026-06-24 15:40:36 +05:30
parent 083beb9780
commit 8f56ac2854
2 changed files with 48 additions and 0 deletions

View File

@@ -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/

View File

@@ -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