What problem does the Flyweight pattern solve?
Flyweight solves the problem of excessive memory consumption, which arises when a system needs to create a huge number of objects of the same type that contain repeated data.
1. The Essence of the Problem
When millions of objects have identical fields (for example, color, font, texture), storing this data in every instance becomes inefficient. Memory is spent duplicating the same information.
2. What Flyweight Does
The pattern splits an object's state into:
- intrinsic - shared across all instances,
- extrinsic - unique and passed in from outside at the point of use.
The intrinsic state is stored in a single shared object that is reused by many clients.
3. Example (Java)
class TreeType {
private String name;
private String color;
private String texture;
public void draw(int x, int y) {
System.out.println("Drawing " + name + " at (" + x + "," + y + ")");
}
}
class TreeFactory {
private static Map<String, TreeType> cache = new HashMap<>();
public static TreeType getTreeType(String name, String color, String texture) {
String key = name + color + texture;
return cache.computeIfAbsent(key, k -> new TreeType(name, color, texture));
}
}
class Tree {
private int x, y; // extrinsic state
private TreeType type; // intrinsic state (shared object)
}Here, millions of Tree objects use the same TreeType (color, texture, shape).
4. The Result
- Memory savings: the shared state is stored in one place.
- Fast work with large collections of objects of the same type.
5. When to Apply It
- In systems with a large number of objects of the same type (graphics, game scenes, glyph caches, text editors).
- When most of the objects' data repeats.
Summary: Flyweight solves the problem of excessive data duplication, letting many objects share common state and thereby sharply reduce memory consumption.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.