Overview
The Flyweight Design Pattern is used to minimize memory usage by sharing as much data as possible with other similar objects. It is especially useful when a large number of objects need to be created that share common data.
Key Characteristics
- Uses shared objects to support a large number of fine-grained objects efficiently.
- Separates intrinsic (shared) and extrinsic (unique) state.
- Reduces memory consumption by reusing existing objects.
Implementation
The following is an example of a Flyweight implementation in Java:
import java.util.HashMap;
import java.util.Map;
// Flyweight interface
interface Shape {
void draw(String color);
}
// Concrete Flyweight
class Circle implements Shape {
private String radius;
public Circle(String radius) {
this.radius = radius;
}
@Override
public void draw(String color) {
System.out.println("Drawing Circle with radius " + radius + " and color " + color);
}
}
// Flyweight Factory
class ShapeFactory {
private static final Map shapes = new HashMap<>();
public static Shape getCircle(String radius) {
Shape circle = shapes.get(radius);
if (circle == null) {
circle = new Circle(radius);
shapes.put(radius, circle);
System.out.println("Creating new Circle with radius: " + radius);
}
return circle;
}
}
// Demo
public class FlyweightDemo {
public static void main(String[] args) {
Shape circle1 = ShapeFactory.getCircle("5");
circle1.draw("Red");
Shape circle2 = ShapeFactory.getCircle("5");
circle2.draw("Blue");
Shape circle3 = ShapeFactory.getCircle("10");
circle3.draw("Green");
}
}
When to Use
- When a large number of objects need to be created and memory usage is a concern.
- When objects can share intrinsic state and only differ in extrinsic state.
Advantages
- Reduces memory usage by sharing common object data.
- Improves performance when handling large numbers of objects.
Disadvantages
- Introduces complexity by separating intrinsic and extrinsic states.
- May not be effective if there is little intrinsic state to share.