Master Software Architecture & Clean Code!
Subscribe to Ram N Java for essential design pattern summaries, clean code tips, and beginner-friendly programming lessons!
SUBSCRIBE NOWOverview of the Flyweight Design Pattern
The Flyweight Pattern is a structural design pattern primarily utilized to reduce memory footprint and prevent object bloat. When an application creates a massive volume of similar objects, storing duplicate data across instances quickly leads to memory exhaustion.
The pattern solves this bottleneck by sharing common object instances across operations rather than instantiating new objects repeatedly.
Essential Key Points You Must Know
- Drastic Memory Optimization: Reuses existing, fine-grained objects to keep heap memory usage low and prevent
OutOfMemoryErrorexceptions in large systems. - Separation of State:
- Intrinsic State: Invariant, shared data stored permanently inside the flyweight object.
- Extrinsic State: Context-dependent data passed in dynamically by the client at runtime.
- Immutability: The intrinsic state of a flyweight instance must remain immutable so that concurrent operations cannot accidentally alter shared data.
- Centralized Object Factory: A flyweight factory maintains a lookup cache/pool to manage and return existing instances efficiently.
- Trade-Off (CPU vs Memory): Saves substantial memory at the cost of slight runtime lookup overhead and passing extrinsic data across method calls.
When to Use Flyweight
Adopt the Flyweight pattern when:
- An application instantiates a massive number of small objects.
- High memory consumption creates a noticeable performance bottleneck.
- Most object properties can be separated into shared intrinsic properties and calculated extrinsic values.
Watch More Related Structural Pattern Tutorials
Click here to watch in Youtube : https://www.youtube.com/watch?v=Ht-ieqGMKBk
Click the below Image to Enlarge
See also:
No comments:
Post a Comment