Flyweight
Intent
Fits more objects into RAM by sharing common state between many objects.
Problem
A particle system with millions of particles runs out of memory because each stores its own sprite.
Solution
Split intrinsic (shared, immutable) state from extrinsic (per-use) state and share the intrinsic part.
Real-world analogy
A game forest: thousands of trees share a handful of tree models. Only each tree's position and size are stored separately.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Flyweight — Flyweight stores the intrinsic state shared between many objects.
- 2Context — Context holds the extrinsic, unique state and pairs it with a flyweight.
- 3FlyweightFactory — Flyweight Factory manages a pool and returns an existing flyweight when one matches.
- 4Client — Client calculates or stores the extrinsic state.
Code example
Applicability
Use Flyweight when the program must support huge numbers of similar objects and RAM is tight.
Pros and cons
Pros
- Large memory savings
Cons
- Trades RAM for CPU
- Code becomes more complicated
Check yourself
A text editor renders millions of characters, and the glyph data is identical for most of them.
Saved in this browser only. Part of Structural patterns (0/7).