32 lines
1.3 KiB
Markdown
32 lines
1.3 KiB
Markdown
# 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/
|