Intrinsic vs Extrinsic State in Flyweight
You'll learn how to identify which data can be shared among Flyweight objects and which must remain context-specific.
The Two Types of State
The Flyweight pattern's memory-saving power comes from splitting an object's state into two categories:
Intrinsic state is the data that can be shared across many objects. It's context-independent—the same regardless of where or how the object is used. This state lives inside the flyweight object and never changes.
Extrinsic state is the data that's unique to each usage context. It's context-dependent and varies with each application of the flyweight. This state is stored outside the flyweight and passed in when needed.
A Practical Analogy
Imagine a printing company that produces business cards. The card template design (logo, font style, layout) is intrinsic—it's shared and reused across thousands of cards. The specific name and contact details are extrinsic—unique to each individual card and provided at print time.
The company doesn't create a new template for every card (wasteful). Instead, it stores one template and combines it with different contact information each time.
Identifying State Types
Ask these questions:
- Can this data be shared without affecting correctness? → Intrinsic
- Does this data change with each use or context? → Extrinsic
- Would storing this in every object waste memory? → Consider making it extrinsic
For example, in a text editor displaying characters, the font glyph shape is intrinsic (shareable), while the position on screen and color are extrinsic (context-specific).
Key Takeaway: The Flyweight pattern succeeds by storing intrinsic (shared, unchanging) state inside flyweight objects while keeping extrinsic (context-specific, variable) state external and passing it in as needed.