StructuralTypeScriptverifiedVerified

Flyweight Pattern in TypeScript

Minimizes memory usage by sharing fine-grained objects that represent repeated data, storing intrinsic state once and passing extrinsic state at call time.

How to Implement the Flyweight Pattern in TypeScript

1Step 1: Define the shared intrinsic state

interface CharacterStyle {
  font: string;
  size: number;
  bold: boolean;
}

2Step 2: Create the Flyweight that holds shared state

class Character {
  constructor(
    public readonly char: string,
    public readonly style: CharacterStyle,
  ) {}

  render(x: number, y: number): void {
    console.log(
      `"${this.char}" [${this.style.font} ${this.style.size}px${this.style.bold ? " bold" : ""}] @ (${x},${y})`,
    );
  }
}

3Step 3: Build a factory that pools and reuses flyweights

class CharacterFactory {
  private pool = new Map<string, Character>();

  get(char: string, style: CharacterStyle): Character {
    const key = `${char}|${style.font}|${style.size}|${style.bold}`;
    if (!this.pool.has(key)) {
      this.pool.set(key, new Character(char, style));
      console.log(`[Factory] created flyweight for key "${key}"`);
    }
    return this.pool.get(key)!;
  }

  get poolSize(): number { return this.pool.size; }
}

4Step 4: Render text and verify flyweight reuse

const factory = new CharacterFactory();
const style: CharacterStyle = { font: "Arial", size: 12, bold: false };

// Rendering "ABBA" – "A" and "B" flyweights are reused
const text = ["A", "B", "B", "A"];
text.forEach((ch, i) => factory.get(ch, style).render(i * 10, 0));

console.log("Flyweights in pool:", factory.poolSize); // 2, not 4

Flyweight Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Flyweight Pattern in the Real World

A book publisher doesn’t print a separate metal typeface block for every letter ‘e’ on every page. Instead, one block for ‘e’ (intrinsic state) is reused in every position, with the printer supplying the ink color and position (extrinsic state) each time it is stamped. Thousands of impressions share one piece of metal.