Flyweight
Share intrinsic state among many objects to support large quantities without exhausting memory.
Context
You want to render 1,000,000 particles, each with a sprite, color, and position. If you store the sprite in each particle, you will run out of RAM.
Problem
Distinguish what is intrinsic (sharable — sprite) from what is extrinsic (unique — position) and share the former.
Solution
Create a flyweight factory that reuses instances of intrinsic state. Particles only store extrinsic state + a reference to the flyweight.
#Example in C#
public sealed record ParticleType(string Sprite, string Color); // intrinsic shared
public class ParticleTypeFactory
{
private readonly Dictionary<(string, string), ParticleType> _pool = new();
public ParticleType Get(string sprite, string color)
{
if (!_pool.TryGetValue((sprite, color), out var t))
_pool[(sprite, color)] = t = new ParticleType(sprite, color);
return t;
}
}
public struct Particle // extrinsic
{
public float X, Y, VX, VY;
public ParticleType Type;
}When NOT to apply it
When the cost of managing the pool outweighs the savings, or when the objects are already small.
Tradeoffs
| Pro | Con |
|---|---|
| Huge memory savings | More complex code |
| Improved cache locality | Intrinsic state must be immutable |
#structural #gof #memory