Purpose: Reduces the cost of creating and managing a large number of similar objects. The Flyweight pattern achieves this by sharing objects, which can reduce memory usage and improve performance.
String pool implementation in Java is one
of the best examples of flyweight pattern implementation.
Here are some real-time use cases for the Flyweight Design Pattern:
1. Inventory Management Systems
- Scenario: An inventory management
system needs to handle a large number of similar products with common
attributes but different quantities and locations.
- Flyweight Use Case: Implement a
ProductFactory
to create and reuseProduct
objects with shared intrinsic state (product details, category) and unique extrinsic state (quantity, location). This reduces memory usage and simplifies inventory management.
Consider using this when
- The number of Objects to be created by
application should be huge.
- The object creation is heavy on memory and it
can be time consuming too.
- The object should be immutable
Usage examples:
- May be used to represent the keyboard
characters: one object for ‘a’, one for ‘b’ and so on.
- When drawing a lot of shapes with different
colors: one object for red circle, one object for blue circle and so on.
In case red circle was already created once, there is no need to create
new such object, since the same object may be reused.
No comments:
Post a Comment