Flyweight Pattern: Sharing State for Memory Efficiency
You'll learn how the Flyweight pattern reduces memory usage by sharing common data across many similar objects.
When your application needs thousands or millions of similar objects, creating each one individually can consume enormous amounts of memory. The Flyweight pattern solves this by identifying which parts of an object's state can be shared and which parts must remain unique.
The Core Idea
Think of a text editor displaying a document. Each character on screen is an object with properties like:
- The letter itself (e.g., 'A')
- Font family and size
- Position on screen
If you have 10,000 characters, and each stores its own font information, you're wasting memory—most characters share the same font! The Flyweight pattern separates state into two types:
- Intrinsic state: Shared, immutable data (like font properties)
- Extrinsic state: Unique data that varies per instance (like position)
The Flyweight stores only intrinsic state and shares it across instances. Extrinsic state is passed in from the outside when needed.
How It Works
A Flyweight Factory manages shared flyweight objects. When you request a flyweight (like a character with Arial 12pt font), the factory either returns an existing shared instance or creates a new one if none exists. You provide the extrinsic state (position) separately each time you use the flyweight.
Real-World Analogy
Imagine a library where many readers borrow the same book title. Instead of giving each reader their own physical copy (wasteful), the library shares copies. Each reader's bookmark position is unique (extrinsic), but the book content is shared (intrinsic).
Key Takeaway: The Flyweight pattern dramatically reduces memory usage by sharing immutable common state across many objects while keeping unique state external.