GoF pattern • Structural
GoFStructuralJava example
Flyweight solves a specific structural problem in the design.
Share intrinsic state so many similar objects use less memory.
Pattern overview
GoF pattern
Share intrinsic state so many similar objects use less memory.
Intent
Use sharing to support large numbers of fine-grained objects efficiently.
Problem
A system creates huge numbers of similar objects, and most state is repeatable rather than unique per instance.
Solution
Store shared intrinsic state centrally and pass the changing extrinsic state separately.
Fit and tradeoffs
FamilyGoF
CategoryStructural
Best used when
- When memory pressure comes from repeated immutable data.
- When many objects differ only by a small external context.
Tradeoffs
- Makes object lifecycle and state ownership less obvious.
- Works best when shared state is truly immutable.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
record Glyph(String fontFamily, int size, char symbol) {}
final class GlyphFactory {
private final Map<String, Glyph> cache = new HashMap<>();
Glyph get(String fontFamily, int size, char symbol) {
String key = fontFamily + ":" + size + ":" + symbol;
return cache.computeIfAbsent(key, ignored -> new Glyph(fontFamily, size, symbol));
}
}