The Flyweight pattern is a structural design pattern that aims to minimize memory usage by sharing common state between multiple similar objects. It is used when you need to create a large number of objects that have similar properties, and the memory usage becomes a concern. The Flyweight pattern achieves this by separating the intrinsic (shared) state and extrinsic (unique) state of the objects. Here is an example of implementing the Flyweight pattern in Java:
The Shape interface represents the flyweight interface and declares the draw() method.
The Circle class is a concrete flyweight class that implements the Shape interface. It stores the intrinsic state (color) and can have extrinsic state (position and radius) set by the client.
The ShapeFactory class acts as a flyweight factory. It maintains a cache (in the form of a Map) of already created circles, keyed by their color. When the getCircle() method is called with a color, it either returns an existing circle from the cache or creates a new circle if it does not exist.
The client code in the Client class demonstrates the usage of the flyweight objects. It repeatedly requests circles with random colors and sets their position and radius. The draw() method is then called on each circle, demonstrating the sharing of the common state (color) among multiple circle objects.
By using the Flyweight pattern, you can reduce memory usage by sharing common state among similar objects, which is especially beneficial when dealing with a large number of objects. The intrinsic state is shared, while the extrinsic state can be varied. This pattern helps improve performance and optimize resource usage in memory-constrained scenarios.