Implement Flyweight in Java by separating sharable immutable state from caller-supplied context and reusing flyweights through a factory.
Flyweight: A shared object that stores immutable intrinsic state while the caller supplies context-specific extrinsic state.
In Java, Flyweight works best when the shared state is truly stable and many logical instances reuse it.
1public record GlyphStyle(String font, int size, boolean bold) {}
2
3public final class Glyph {
4 private final GlyphStyle style;
5 private final char symbol;
6
7 public Glyph(GlyphStyle style, char symbol) {
8 this.style = style;
9 this.symbol = symbol;
10 }
11
12 public void draw(int x, int y) {
13 System.out.printf("%s %s at (%d,%d)%n", style, symbol, x, y);
14 }
15}
Here:
style and symbol can be intrinsic1public final class GlyphFactory {
2 private final Map<GlyphKey, Glyph> cache = new HashMap<>();
3
4 public Glyph get(String font, int size, boolean bold, char symbol) {
5 GlyphKey key = new GlyphKey(font, size, bold, symbol);
6 return cache.computeIfAbsent(key,
7 ignored -> new Glyph(new GlyphStyle(font, size, bold), symbol));
8 }
9}
The factory centralizes sharing. Without that factory, the pattern usually does not exist in practice.
Flyweight is worth it when reuse is real and measurable, not just theoretically elegant.