Flyweight

Share the common, unchanging part of many similar objects instead of copying it into each one, to save memory at scale.

Description

Flyweight splits an object's state in two. Intrinsic state is the same for many objects and never changes, such as a pin's icon, colour and heavy SVG path. It lives in a shared, immutable flyweight. Extrinsic state differs per object, such as position and label, and stays with each object or is passed in when needed.

A flyweight factory hands out one shared instance per distinct combination. Ten thousand pins of three kinds then hold three style objects instead of ten thousand copies. The same idea powers string interning, glyph caches in text editors and sprite sheets in games.

Class diagram

sharescaches«interface»Pin+ x, y: number+ label: string+ style: PinStylePinStyles- cache: Map<string, PinStyle>+ get(icon, color): PinStyle+ count: numberPinStyle+ icon, color+ svgPath (large)+ draw(x, y, label)

Flyweight pattern class diagram

  1. Interface Pin.
  2. Class PinStyles with + get(icon, color): PinStyle, + count: number.
  3. Class PinStyle with + draw(x, y, label).
  4. Pin shares PinStyle.
  5. PinStyles caches PinStyle.

Sequence diagram

Map loaderPinStylescafe styleopt[first time]1. get("cafe", "brown")2. new PinStyle(…)3. cafe style4. get("cafe", "brown")5. same cafe style6. draw(x, y, label)

Flyweight pattern sequence diagram

  1. Map loader → PinStyles: get("cafe", "brown").
  2. PinStyles → cafe style: new PinStyle(…).
  3. Map loader receives "cafe style" back from PinStyles.
  4. Map loader → PinStyles: get("cafe", "brown").
  5. Map loader receives "same cafe style" back from PinStyles.
  6. Map loader → cafe style: draw(x, y, label).

TypeScript example

Ten thousand map pins that share three style objects. Each pin keeps only its position and label; the heavy, unchanging style is shared and frozen.

flyweight.ts
// Flyweight: 10,000 map pins share a handful of style objects.

// Flyweight: intrinsic, shared, immutable state
class PinStyle {
  readonly icon: string;
  readonly color: string;
  readonly svgPath: string; // imagine a large SVG string here
  constructor(icon: string, color: string) {
    this.icon = icon;
    this.color = color;
    this.svgPath = `M0 0 L10 20 ... (${icon})`;
  }
  draw(x: number, y: number, label: string): string {
    return `${this.icon} ${this.color} at (${x}, ${y}) "${label}"`;
  }
}

// Flyweight factory: hands out one shared instance per distinct style
class PinStyles {
  private readonly cache = new Map<string, PinStyle>();
  get(icon: string, color: string): PinStyle {
    const key = `${icon}|${color}`;
    let style = this.cache.get(key);
    if (!style) {
      style = Object.freeze(new PinStyle(icon, color));
      this.cache.set(key, style);
    }
    return style;
  }
  get count(): number {
    return this.cache.size;
  }
}

// Context: extrinsic, per-pin state plus a reference to a shared style
interface Pin {
  x: number;
  y: number;
  label: string;
  style: PinStyle;
}

export function demo(): string[] {
  const styles = new PinStyles();
  const kinds = [
    ["cafe", "brown"],
    ["shop", "teal"],
    ["office", "slate"],
  ] as const;

  const pins: Pin[] = [];
  for (let i = 0; i < 10_000; i++) {
    const [icon, color] = kinds[i % kinds.length];
    pins.push({ x: i % 100, y: Math.floor(i / 100), label: `${icon} #${i}`, style: styles.get(icon, color) });
  }

  return [
    `${pins.length} pins, ${styles.count} style objects`,
    pins[4].style.draw(pins[4].x, pins[4].y, pins[4].label),
    `pins 0 and 3 share a style: ${pins[0].style === pins[3].style}`,
  ];
}

When to use it

Use it when

  • You create a very large number of similar objects, and memory or garbage collection is a measurable problem.
  • Most of each object's data is duplicated and can be made immutable.
  • The objects can get their varying data from outside, through fields on a light context object or method arguments.

Avoid it when

  • You have hundreds of objects, not hundreds of thousands. The savings won't matter and the split adds complexity.
  • The shared part needs to change per object. Then it isn't intrinsic.
  • You haven't measured a memory problem. Optimise when profiling says so.

Pitfalls

  • Mutating a shared flyweight, which silently changes every object using it. Freeze flyweights.
  • Unbounded factory caches that grow forever. Bound them if the set of keys is open-ended.
  • Spreading extrinsic state across many call sites makes code harder to read. Keep the split in one place.

Alternatives

Singleton

Choose it when you need exactly one shared instance, not one per distinct value.

Prototype

Choose it when objects should be independent copies that can change, not shared immutable parts.

Plain caching / memoization

Choose it when you want to avoid recomputing values, not reduce the size of many live objects.