Command Palette

Search for a command to run...

PHASE 2Beginner ~7 min· topic 12 of 22Structural

Structural 7 — Flyweight

In one line

Share the intrinsic (immutable, common) part of many fine-grained objects and pass the extrinsic (per-use) part in, so a million objects cost the memory of a few hundred.

0/22 · 0%

Think of it like this

Letters in a printed book. The printer has one metal 'e' shape and stamps it thousands of times in different places. The shape is shared; only its position changes.

Key ideas

  1. 01

    Solves: memory blow-up from huge numbers of similar objects, such as characters in a text editor, trees in a game map, or chess pieces across millions of stored games.

  2. 02

    Intrinsic state: shared and immutable (glyph shape, font, piece colour+type). Extrinsic state: per instance and supplied by the caller (position, row/column).

  3. 03

    A flyweight factory caches instances by key and returns the shared one. The flyweights must be immutable, or sharing becomes a bug.

  4. 04

    Java does this itself: Integer.valueOf(-128..127), Boolean.TRUE, and String interning.

  5. 05

    Interview angle: a text editor storing 10M characters shares ~100 glyph objects and stores only (char, position, styleRef) per character.

Java / Spring map

  • →

    Integer.valueOf caching; String.intern(); enum constants are the ultimate flyweights.

Code & diagrams

Flyweight.javajava

Chess pieces: 12 shared objects serve every board in memory.

public enum Color { WHITE, BLACK }
public enum Kind { KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN }

// Flyweight: intrinsic, immutable, shared
public record PieceType(Color color, Kind kind) {}

public final class PieceTypes {
  private static final Map<String, PieceType> CACHE = new ConcurrentHashMap<>();
  public static PieceType of(Color c, Kind k) {
    return CACHE.computeIfAbsent(c + ":" + k, key -> new PieceType(c, k));
  }
}

// Extrinsic state lives in the board, not the piece
public final class Board {
  private final PieceType[] squares = new PieceType[64];   // 64 references, 12 objects max
  public void place(int sq, Color c, Kind k) { squares[sq] = PieceTypes.of(c, k); }
}
// 1M boards in memory → ~64M references, but still only 12 PieceType objects.

Explain without notes

01

Which state is intrinsic and which is extrinsic in a text editor's character objects?

Practice

01

Design the glyph flyweight for a text editor and estimate memory saved for a 5M-character document.

Trade-offs

  • ↔

    Saves memory at the cost of complexity: callers must pass extrinsic state, and shared objects must stay strictly immutable.

Completion checklist

  • I can separate intrinsic and extrinsic state and implement a flyweight factory.

Back to phase