Flyweight
Intent
Share one copy of heavy repeated state across many small objects, keeping per-item data tiny so large collections stay cheap.
Motivation
A text view renders 1000 glyphs, but only two font styles appear: bold and italic. Storing a full font description inside every glyph repeats the same heavy data a thousand times and bloats memory. A flyweight factory keeps one shared record per style and hands the same record to every glyph using it, so 1000 glyphs reference just 2 shared styles and reuse the font data 998 times.
Structure
flowchart LR View --> Factory[Style Factory] Factory --> Bold[Shared Bold Style] Factory --> Italic[Shared Italic Style] View --> Glyph[Glyph x1000] Glyph --> Bold Glyph --> Italic
- Flyweight (Font Style) — the shared, heavy, reusable state.
- Factory — hands out one record per style and reuses it on repeat requests.
- Context (Glyph) — a lightweight item holding its position plus a reference to a shared style.
- Client (View) — requests styles through the factory instead of building new copies.
Consequences
- Benefit: memory drops sharply when shared state dominates and repeats — 1000 glyphs cost 2 style records.
- Cost / trade-off: shared records must stay unchangeable (or carefully guarded); splitting shared from per-item state adds design effort.
Basic Recap
Flyweight reduces memory use by sharing immutable state common to many small objects. The shared intrinsic state lives in a flyweight, while varying extrinsic state is supplied by the context or caller. A factory usually interns flyweights by a value key so equivalent requests receive the same instance. Correctness depends on keeping shared objects immutable and separating identity from the reusable representation.
Complex Scenario
A logistics dashboard renders hundreds of thousands of vehicle markers on map
tiles. Markers share icon images, color palettes, and label fonts, but each has a
different position, heading, and vehicle identifier. An IconStyleFactory
returns one immutable style per visual key, and lightweight marker contexts hold
only dynamic values. Rendering passes the extrinsic state to the shared style
instead of storing a full icon and font description in every vehicle.
Edge cases
- Memory pressure: An unbounded style cache can recreate the problem it was meant to solve, especially when keys include tenant-specific colors; capacity and eviction must account for native image resources.
- Concurrency: Simultaneous requests for one style should not leak duplicate native allocations, and publishing a style must happen only after it is fully decoded.
- Partial failure: If an icon cannot load, markers need a bounded fallback style rather than caching a broken object forever or retrying once per marker.
Profile before applying the pattern: shared keys and object lifetime determine whether flyweights save memory or merely add cache coordination.
Sketch (illustrative pseudocode, not runnable):
styleKey = StyleKey(iconHash, paletteId, fontId)
style = styles.intern(styleKey, factory = loadImmutableStyle)
Marker.render(canvas):
style.draw(
canvas,
position = this.position,
rotation = this.heading,
label = this.vehicleId
)
Styles.evictWhenOverBudget():
removeUnreferencedStyles()
releaseNativeImagesForRemovedEntries()
When to Use / When Not to Use
Use when:
- Many items repeat a small set of heavy states (glyphs, tiles, particles with shared textures).
- Shared state can be kept immutable and looked up cheaply.
Avoid when:
- Items barely repeat — the factory and lookup cost outweigh the savings.
- The “shared” state keeps changing per item, forcing copies anyway.
Examples
Links to runnable code (same scenario, four languages):
examples/elixir/flyweight/examples/dart/flyweight/examples/go/flyweight/examples/rust/flyweight/
Expected outcome: rendering 1000 glyphs reports 2 shared styles and the reuse count.
Anti-pattern / Failure Mode
-
Misuse: Sharing state that is rarely repeated, adding lookup cost for no gain.
-
Review signal: Shared state mutated through one user affecting others.
-
Misuse symptom: Vehicle position, selection, or other mutable state is put into the shared style to make drawing calls shorter, causing unrelated markers to change together. Another symptom is interning values that are almost never equal, producing a large cache with little actual reuse.
-
Review signal: Look for setters on flyweights, cache keys containing unique request data, and factory dictionaries without eviction or concurrency tests. Memory profiles should distinguish shared intrinsic bytes from the growing key and context population; an object-count reduction alone is not proof of a smaller heap or native footprint.
Related
- Prototype — share repeatable state vs clone a tuned copy.
- Singleton — one shared owner vs many shared values.
- Bounded Resource — share to bound memory.
Exercise
Add a third style (underline) used by 50 of the glyphs. The factory must still hold exactly 3 shared records, and the reuse count must update accordingly.
Self-check
- What is shared vs per-glyph?
Answer
Font style records are shared; each glyph keeps only its own position and a style reference. - Why must shared state stay immutable?
Answer
One edit would leak into every glyph using that record — sharing requires stability. - When does Flyweight lose?
Answer
When states rarely repeat; then the cache saves little and adds lookup overhead.