design patterns
Flyweight
The Flyweight pattern uses sharing to support large numbers of fine-grained objects efficiently. It minimizes memory usage by sharing as much data as possible with similar objects. The key participants are the Flyweight (declares an interface through which flyweights can receive and act on extrinsic state), ConcreteFlyweight (stores intrinsic state that is shareable), FlyweightFactory (creates and manages flyweight objects, ensuring they are shared properly), and Client (maintains extrinsic state and passes it to the flyweight). Think of characters in a text editor: the letter 'A' object is shared everywhere it appears — only its position (extrinsic state) differs. Use Flyweight when an application uses a large number of objects that have some shared state, and most object state can be made extrinsic (stored outside the object).
Use Cases
- •Text rendering engines sharing character glyph data
- •Game development with many similar objects (trees, particles)
- •Caching and pooling frequently used immutable objects
- •Map applications reusing icons for the same type of marker