Flyweight
Shares common state between multiple objects to reduce memory usage.
Understanding Flyweight
The Flyweight pattern dramatically reduces memory usage by sharing common state between many similar objects instead of storing it redundantly in each one. It separates an object's state into intrinsic (shared, immutable) and extrinsic (unique per context) parts. In Go, a flyweight factory (usually using a map cache) creates and returns shared instances keyed by their intrinsic properties. This is essential for applications that create millions of similar objects — like characters in a text editor, particles in a game, or tree types in a forest renderer.
Key Concepts
- •Intrinsic state — shared data stored inside the flyweight object (e.g., tree type, font style) — immutable and reused
- •Extrinsic state — unique data stored outside the flyweight by the client (e.g., position, context) — passed to methods
- •Flyweight factory — ensures flyweight objects are shared by caching and returning existing instances from a map
- •Memory savings — instead of N objects × M bytes each, you have K shared flyweights + N lightweight contexts
When to Use
- • Your application creates a very large number of similar objects
- • Most of each object's state can be made extrinsic (passed from outside)
- • Groups of objects share substantial portions of their state
- • The application struggles with memory consumption from many object allocations
- • Objects have mostly unique state that can't be shared
- • The number of objects is small enough that memory isn't a concern
- • The complexity of separating intrinsic/extrinsic state isn't worth the savings
Structure
How It Works
Memory Problem
Creating many similar objects consumes lots of memory.
Basic Implementation
Forest rendering with shared tree type objects:
Real-World Example: Text Editor
Character formatting with shared format objects: