Flyweight Pattern
Fit more objects into the available amount of RAM by sharing common parts of state between multiple objects.
Intent & Objective
Share common immutable state (intrinsic state) among multiple objects instead of keeping duplicate data in each individual object, dramatically reducing memory consumption.
"Instead of printing a brand new physical book for every reader in town, the library keeps one copy and shares it among hundreds of readers over time."
"Multiple passengers share the same vehicle or bicycle rather than every person manufacturing and operating their own private hardware."
"Multiple software applications running concurrently link against the exact same shared library DLL in RAM instead of duplicating memory footprints."
The Problem
Out of memory errors when creating millions of fine-grained objects that share largely identical data.
The Solution
Split object state into Intrinsic (shared, constant, stored in Flyweight) and Extrinsic (context-specific, unique, passed in at call time by client).
Key Participants & Architectural Roles
Code Samples (Traditional OOP vs Functional Programming)
Available in C++, Python, and JavaParadigm Contrast: Traditional OOP vs Functional / Data-Oriented
In OOP, Flyweight is a shared object factory with a cache map. In Functional Programming, Flyweight is structural sharing and string/symbol interning, natural to pure immutable environments.
Advantages
- ✓ Massively conserves RAM when working with huge numbers of similar objects
Trade-offs
- ✗ Trades RAM savings for minor CPU computation when stripping/passing extrinsic state
When to Apply
- → When your application spawns an enormous number of objects and available RAM is insufficient
When to Avoid
- ! When you only have a few hundred or thousand objects where memory is plenty