Catalog / Structural Patterns / Flyweight Pattern
STRUCTURAL

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.

👥 Real-World Human Analogies & Social Roles
3 Intuitive Scenarios
Public Library Books Resource Sharing

"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."

Carpooling & Shared Bicycles Urban Transit

"Multiple passengers share the same vehicle or bicycle rather than every person manufacturing and operating their own private hardware."

Shared OS Utility Libraries Developer Daily Life

"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

Flyweight
Contains intrinsic (shared) state that doesn’t depend on context
Flyweight Factory
Creates and caches flyweights, reusing existing ones
Context
Contains extrinsic state unique across all objects and holds flyweight reference

Code Samples (Traditional OOP vs Functional Programming)

Available in C++, Python, and Java

Paradigm 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