design patterns ·
Flyweight
Uses sharing to support large numbers of fine-grained objects efficiently by separating intrinsic and extrinsic state.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
When you have millions of similar objects (game particles, text glyphs, map tiles), most of their state is shared (intrinsic) and only a small part differs per instance (extrinsic). Flyweight shares the intrinsic state via a factory cache.
Intrinsic state is context-independent and shared (color, sprite). Extrinsic state is context-dependent and passed in (position, velocity). The FlyweightFactory caches and returns shared flyweight instances by key.
When to use
Text editors (shared character glyphs), game development (shared tile/sprite data), caching font or icon objects, large-scale particle systems - anywhere millions of similar objects would be created.
When not to
When the number of objects is small. When objects do not share significant state.
Key insights
- Flyweight trades CPU (extrinsic state lookup) for memory (shared intrinsic objects)
- The factory uses a map keyed by intrinsic state to return cached flyweights
- Java String pool is a real-world Flyweight implementation
- Must ensure flyweight objects are truly immutable - shared objects must not be mutated