Real World Example
Did you ever have fresh tea from some stall? They often make more than one cup that you demanded and save the rest for any other customer so to save the resources e.g. gas etc. Flyweight pattern is all about that i.e. sharing.
In Plain Words
It is used to minimize memory usage or computational expenses by sharing as much as possible with similar objects.Wikipedia Definition
In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.
Programmatic Example
Translating our tea example from above. First of all we have tea types and tea maker:TeaShop which takes orders and serves them:
Key Participants
Flyweight
Flyweight
Declares an interface through which flyweights can receive and act on extrinsic state (in our example:
KarakTea)Flyweight Factory
Flyweight Factory
Creates and manages flyweight objects and ensures proper sharing (in our example:
TeaMaker)Client
Client
Maintains references to flyweights and computes/stores extrinsic state (in our example:
TeaShop)Intrinsic vs Extrinsic State
Intrinsic State: Stored in the flyweight; it’s independent of the flyweight’s context and sharable.Extrinsic State: Depends on and varies with the flyweight’s context and therefore cannot be shared.
- Intrinsic: The tea type itself (stored in flyweight)
- Extrinsic: The table number (stored by client)
Memory Savings Visualization
Without Flyweight
With Flyweight
When to Use?
Use the Flyweight pattern when:
- An application uses a large number of objects
- Storage costs are high because of the sheer quantity of objects
- Most object state can be made extrinsic
- Many groups of objects may be replaced by relatively few shared objects
- The application doesn’t depend on object identity
Benefits
- Memory Reduction: Can save huge amounts of memory when dealing with large numbers of similar objects
- Performance: Reduces object creation overhead
- Centralized State: Shared intrinsic state is kept in one place
Considerations
Real-World Applications
Text Editors
Characters in documents - each character type is a flyweight
Game Development
Trees, bullets, particles - sharing textures and models
String Pools
String interning in Java, Python to reuse string objects
Database Connections
Connection pooling reuses database connections
Example: Text Formatting
Pattern Implementation Checklist
Related Patterns
- Composite: Flyweight is often combined with Composite to implement shared leaf nodes
- State and Strategy: These can be implemented as Flyweights
- Singleton: Flyweight factory is often a Singleton