Flyweight Pattern: Sharing to Support Many Objects
What you'll learn: How the Flyweight pattern dramatically reduces memory consumption when you need thousands of similar objects by sharing their common data.
The Core Problem
Imagine a word processor rendering a document with 10,000 characters. If each character object stores its font, size, color, and style independently, you'd have massive memory overhead—even though most characters share the same formatting.
The Flyweight pattern solves this by splitting object state into two types:
- Intrinsic state: shared, immutable data (e.g., font family, size)
- Extrinsic state: unique, context-dependent data (e.g., character position)
How It Works
Instead of each object storing everything, flyweights store only the intrinsic state. The extrinsic state is passed in when needed. A factory manages a pool of flyweight instances, returning existing ones when possible.
Analogy: Think of a library card system. The library (factory) has one copy of each book (intrinsic state). When you check out a book, you provide your name and due date (extrinsic state). Thousands of people can "use" the same book without needing thousands of physical copies.
When to Use Flyweight
- You have many objects (hundreds or thousands)
- Most of their state can be made extrinsic
- Memory consumption is a genuine concern
- Object identity doesn't matter (sharing is acceptable)
Practical Examples
- Text editors (shared character formatting)
- Game engines (shared textures, particle effects)
- GUI toolkits (reusable graphical primitives)
Key Takeaway: The Flyweight pattern trades computation (looking up shared objects) for memory savings by extracting and sharing the common state across many fine-grained objects—essential when you need to support vast quantities efficiently.