Skip to content
BBaskaran

Flyweight

Share common state between many objects to save memory.

Use it when

An application creates huge numbers of similar objects.

/**
 * Flyweight: thousands of map markers share a handful of heavy icon objects.
 *
 * Real-world scenario: a maps app shows 10,000 places. Each marker has its own
 * position, but there are only three kinds of icon (restaurant, hotel, fuel), and
 * each icon image is large. Instead of loading an image per marker, markers share
 * one icon object per kind, created on first use by a small factory.
 *
 * Shared (intrinsic) state lives in the flyweight: kind, colour, image.
 * Unique (extrinsic) state stays in each marker: its latitude and longitude.
 */

const ICON_SIZE_KB = 50;
const ICON_COLORS: Record<string, string> = { restaurant: "red", hotel: "blue", fuel: "green" };

// Flyweight: shared, read-only state, so no marker can change it.
class MarkerIcon {
  readonly kind: string;
  readonly color: string;
  readonly image: Uint8Array;

  constructor(kind: string, color: string, image: Uint8Array) {
    this.kind = kind;
    this.color = color;
    this.image = image;
  }

  draw(lat: number, lng: number): string {
    return `${this.color} ${this.kind} pin at (${lat.toFixed(4)}, ${lng.toFixed(4)})`;
  }
}

// Flyweight factory: hands out an existing icon, creating it only once.
class IconFactory {
  private readonly icons = new Map<string, MarkerIcon>();

  get(kind: string): MarkerIcon {
    let icon = this.icons.get(kind);
    if (!icon) {
      console.log(`Loading ${kind} icon (${ICON_SIZE_KB} KB)`);
      const image = new Uint8Array(ICON_SIZE_KB * 1024); // stands in for a real image file
      icon = new MarkerIcon(kind, ICON_COLORS[kind], image);
      this.icons.set(kind, icon);
    }
    return icon;
  }

  get count(): number {
    return this.icons.size;
  }
}

// Context: the unique part of each marker, plus a reference to a shared icon.
class Marker {
  readonly lat: number;
  readonly lng: number;
  readonly icon: MarkerIcon;

  constructor(lat: number, lng: number, icon: MarkerIcon) {
    this.lat = lat;
    this.lng = lng;
    this.icon = icon;
  }

  draw(): string {
    return this.icon.draw(this.lat, this.lng);
  }
}

function clientCode(): void {
  const icons = new IconFactory();
  const kinds = ["restaurant", "hotel", "fuel"];

  const markers = Array.from(
    { length: 10_000 },
    (_, i) => new Marker(51.5 + i * 0.0001, -0.12 + i * 0.0001, icons.get(kinds[i % 3])),
  );

  for (const marker of markers.slice(0, 3)) {
    console.log(marker.draw());
  }

  console.log(`Markers: ${markers.length.toLocaleString("en-US")}, icon objects: ${icons.count}`);
  console.log(`Same icon object shared: ${markers[0].icon === markers[3].icon}`);
  console.log(`Icon memory: ${icons.count * ICON_SIZE_KB} KB shared`);
  console.log(`Without sharing: ${(markers.length * ICON_SIZE_KB).toLocaleString("en-US")} KB`);
}

clientCode();

// Output:
// Loading restaurant icon (50 KB)
// Loading hotel icon (50 KB)
// Loading fuel icon (50 KB)
// red restaurant pin at (51.5000, -0.1200)
// blue hotel pin at (51.5001, -0.1199)
// green fuel pin at (51.5002, -0.1198)
// Markers: 10,000, icon objects: 3
// Same icon object shared: true
// Icon memory: 150 KB shared
// Without sharing: 500,000 KB

How it works

RoleClassesWhat it does
FlyweightMarkerIconShared, read-only state: kind, colour and the heavy image
Flyweight factoryIconFactoryReturns the existing icon for a kind from a Map, creating it only once
ContextMarkerIts own position, plus a reference to a shared icon
ClientclientCode()Creates 10,000 markers that share just 3 icon objects