Flyweight
Category
Structural pattern
Problem
Reduce memory usage by sharing as much data as possible with similar objects. Useful when you need to support a large number of fine-grained objects that are too memory-intensive.
Solution
- Separate intrinsic state (shared, invariant) from extrinsic state (context-dependent, unique)
- Create a flyweight factory that caches and reuses flyweight objects
- Store extrinsic state outside the flyweight object
Structure
- Flyweight: Interface for flyweight objects; defines operations that accept extrinsic state
- ConcreteFlyweight: Implements Flyweight; stores intrinsic state
- FlyweightFactory: Creates and manages flyweight objects; ensures sharing
- Client: Stores and computes extrinsic state; passes it to flyweight operations
Key Benefits
- Massive memory reduction — Shares data across many objects
- Efficient object creation — Factory caches and reuses objects
Trade-offs
- Complexity — Requires careful separation of intrinsic and extrinsic state
- Computation cost — Transferring extrinsic state in and out can be expensive
When to Use
- An application uses a large number of objects
- Storage cost is high because objects are too similar in state
- Most object state can be made extrinsic
- Few groups of objects can be replaced by shared flyweights