The Flyweight Pattern is a structural design pattern that minimizes memory usage by sharing common parts of state between multiple objects.
The Flyweight Pattern reduces memory usage by sharing as much data as possible between similar objects. This is achieved by separating intrinsic (shared) and extrinsic (unique) states.
Key features:
- Shared State: Intrinsic state is shared between objects.
- Reduced Memory Usage: Minimize memory overhead by reusing existing objects.
- Performance Optimization: Suitable for large numbers of similar objects.
- Memory Efficiency: Reduces memory consumption for large numbers of objects.
- Reusability: Encourages reuse of shared states.
- Performance: Optimizes performance in scenarios with many similar objects.
The implementation of the Flyweight Pattern can be found in:
Shapes.java
: Common interface for all shapes.Circle.java
: Concrete flyweight class.ShapeFactory.java
: Factory for managing flyweights.Main.java
: Demonstrates the usage of the Flyweight Pattern.
To see the Flyweight Pattern in action, refer to the Main.java
file. It demonstrates how to reuse shapes with shared properties.
classDiagram
direction LR
class Client {
}
class Flyweight {
+method(extrinsicState)
}
class FlyweightFactory {
+getID(key)
+cache: Flyweight[]
}
class SharedFlyweight {
-intrinsicState1
-intrinsicState2
+method(extrinsicState)
}
class UnsharedFlyweight {
-intrinsicState1
-intrinsicState2
-extrinsicState1
-extrinsicState2
+method(extrinsicState)
}
Client --> Flyweight : Flyweight
Flyweight <|-- SharedFlyweight
Flyweight <|-- UnsharedFlyweight
Client --> FlyweightFactory
FlyweightFactory --> SharedFlyweight : << create & share >>
Note
If the UML above is not rendering correctly, you can view the diagram from the flyweight_uml.png
file.
- The Flyweight Pattern is ideal for optimizing memory usage when dealing with many similar objects.
- Use it when you need a large number of objects that share most of their state.
- It reduces memory overhead by sharing intrinsic state between objects.