
The Cost of Repetition
Imagine a video game with a forest of 10,000 trees. Each tree has a “Type” (Oak, Pine), a “Texture,” and a “3D Model.” If you create 10,000 unique Tree objects, each carrying its own texture data, your game will crash from an OutOfMemoryError.
The Solution: Sharing is Caring
The Flyweight pattern splits an object’s state into two parts:
- Intrinsic State: Data that is shared across thousands of instances (e.g., the Texture or the Model).
- Extrinsic State: Data that is unique to each instance (e.g., its X, Y, Z coordinates).
The Architecture:
You create one “Flyweight” object for each type of tree. Then, the 10,000 instances just store their coordinates and a reference to that one shared Flyweight.
Real-World Example: Text Editors
Think about a document with 1,000,000 characters. If every character (a, b, c) was a separate object storing its font, size, and color, Microsoft Word would need 64GB of RAM to open a simple letter. Instead, it uses Flyweights to store the font “Metadata” once and share it across all characters.
Conclusion
The Flyweight pattern is all about structural efficiency. When you have high-volume data with heavy repetition, don’t duplicate—link.
References & Further Reading
- Refactoring Guru: Flyweight Design Pattern
- Game Programming Patterns: Flyweight
- DZone: Flyweight Pattern in Java