Skip to content

Flyweight Pattern: Share Immutable State Across Many Objects

Learn the Flyweight pattern through a 68,000-seat arena map that shares seat types instead of copying them, with TypeScript, Python and PHP code.

12 min readDesign patternStructural

Cut memory use when a program needs huge numbers of similar objects by storing the shared, immutable state (intrinsic) once in flyweight objects, and passing the per-object state (extrinsic) in from outside when it is needed.

Flyweight is the pattern you reach for when you have a very large number of small objects and most of their data is identical. You pull the repeated, unchanging part out into a few shared objects and let each small object keep only what makes it unique. In interviews it shows up in questions about memory pressure, caching and object identity. This guide follows one ticketing app from the memory problem to working code, so you can explain the intrinsic versus extrinsic split, the factory that guarantees sharing, and the trade-offs you accept.

The problem

A situation where the obvious design starts to hurt.

You work on SeatLoop, a ticketing app used by box-office staff at Harbour Arena. The interactive seat map shows all 68,000 seats so staff can sell, hold and reprint tickets. The first version created one Seat object per seat, and every Seat carried its full description: tier name, price in cents, colour, and an inline SVG icon for the seat style.

The arena only has six kinds of seat: Floor, Lower Bowl, Upper Bowl, Balcony, Accessible and Companion. Yet every one of the 68,000 objects held its own copy of the tier string, the colour and roughly 2 KB of SVG. That is around 136 MB of duplicated data, all to describe six things. On the cheap Android tablets the box office uses, the app was killed by the OS whenever a staff member opened the full arena view during a sell-out.

The data that actually differs between seats is small: row, seat number, x and y on the map, and whether the seat is sold. You need to keep 68,000 seats addressable without paying for 68,000 copies of the same six descriptions.

The solution

What the pattern proposes.

Split each seat's data into two parts. The intrinsic state is the part that is the same for every seat of a kind and never changes: tier, price, colour and icon. Move it into an immutable SeatType class. That class is the flyweight. Only six instances ever exist.

The extrinsic state is what varies per seat: row, number, coordinates and sold status. Keep it in a tiny Seat context object that holds those fields plus a reference to its shared SeatType. When the map draws a seat, the Seat calls seatType.render(row, number, x, y, sold), handing over its own extrinsic data.

To make sure nobody accidentally creates a seventh copy of Floor, all SeatType instances come from a SeatTypeFactory. It keeps a cache keyed by the intrinsic values and returns the existing instance when one matches, creating a new one only on the first request. The SeatMap builds seats through that factory.

The result: six SeatType objects at about 2 KB each, plus 68,000 small context records holding a few numbers and a pointer. The SVG payload drops from about 136 MB to about 12 KB, and the tablets stop crashing.

An everyday analogy

The same idea, outside software.

Think of a library with a hundred copies of the same printed reading list taped inside a hundred lockers, versus one laminated list on the wall plus a sticky note in each locker saying which pages that student has finished. The laminated list is shared and nobody writes on it. The sticky notes are tiny and personal. Each student reads the shared list together with their own note to know what to do next. If the reading list were written on, everyone's view would change, which is exactly why the shared part must stay read-only.

Structure

The pieces and how they relate.

SeatMap asks SeatTypeFactory for shared SeatType flyweights; each Seat keeps its own position and status and points to one SeatType.Box-office UI calls SeatMap (render()). SeatMap has a Seat (68,000 seats). SeatMap calls SeatTypeFactory (get(...)). SeatTypeFactory creates SeatType (on cache miss). SeatTypeFactory has a SeatType (cache). Seat calls SeatType (render(extrinsic)).Box-office UIopens the arena viewSeatMapaddSeat(), sell(),render()Seatrow, number, x, y,soldSeatTypetier, priceCents,colour, iconSvgSeatTypeFactoryget(tier, price,colour, icon)6 flyweightsshared by 68,000Seat contextsrender()68,000 seatsget(...)on cache misscacherender(extrinsic)
SeatMap asks SeatTypeFactory for shared SeatType flyweights; each Seat keeps its own position and status and points to one SeatType.

Participants

Flyweight (SeatType)
Holds the intrinsic state shared by many seats: tier, price, colour and icon. It is immutable, and its methods take the extrinsic state as parameters instead of storing it.
Context (Seat)
Stores the extrinsic state that is unique to one seat (row, number, coordinates, sold flag) plus a reference to its flyweight. It delegates rendering to the flyweight, passing its own data in.
Flyweight Factory (SeatTypeFactory)
Owns a cache of flyweights keyed by their intrinsic values. Returns an existing instance when one matches and creates a new one only on a miss, which is what guarantees sharing.
Client (SeatMap)
Builds and manages the contexts. It never constructs a SeatType directly; it asks the factory and attaches the result to each new Seat.

Pseudocode

The solution to the scenario, language-neutral.

class SeatType  // flyweight, immutable
  field tier, priceCents, colour, iconSvg

  method render(row, number, x, y, sold)
    fill = sold ? GREY : colour
    return description using tier, price, x, y, fill

class SeatTypeFactory
  field cache = empty map

  method get(tier, priceCents, colour, iconSvg)
    key = tier + priceCents + colour + iconSvg
    if key not in cache
      cache[key] = new SeatType(tier, priceCents, colour, iconSvg)
    return cache[key]

class Seat  // context, extrinsic state
  field row, number, x, y, sold = false
  field seatType

  method render()
    return seatType.render(row, number, x, y, sold)

class SeatMap
  field factory, seats = ordered map

  method addSeat(row, number, x, y, tier, priceCents, colour, iconSvg)
    type = factory.get(tier, priceCents, colour, iconSvg)
    seats[row + number] = new Seat(row, number, x, y, type)

  method sell(row, number)
    seats[row + number].sold = true

  method render()
    return [seat.render() for each seat in seats]

// 68,000 calls to addSeat, but factory.cache ends up with 6 entries

The code

The same solution in TypeScript, Python and PHP.

class SeatType {
  constructor(
    readonly tier: string,
    readonly priceCents: number,
    readonly colour: string,
    readonly iconSvg: string,
  ) {}

  render(row: string, number: number, x: number, y: number, sold: boolean): string {
    const fill = sold ? "#9e9e9e" : this.colour;
    const price = (this.priceCents / 100).toFixed(2);
    return `${row}${number} [${this.tier} $${price}] at (${x},${y}) fill=${fill}`;
  }
}

class SeatTypeFactory {
  private readonly cache = new Map<string, SeatType>();

  get(tier: string, priceCents: number, colour: string, iconSvg: string): SeatType {
    const key = `${tier}|${priceCents}|${colour}|${iconSvg}`;
    let seatType = this.cache.get(key);
    if (seatType === undefined) {
      seatType = new SeatType(tier, priceCents, colour, iconSvg);
      this.cache.set(key, seatType);
    }
    return seatType;
  }

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

class Seat {
  sold = false;

  constructor(
    readonly row: string,
    readonly number: number,
    readonly x: number,
    readonly y: number,
    readonly seatType: SeatType,
  ) {}

  render(): string {
    return this.seatType.render(this.row, this.number, this.x, this.y, this.sold);
  }
}

class SeatMap {
  private readonly seats = new Map<string, Seat>();

  constructor(private readonly factory: SeatTypeFactory) {}

  addSeat(row: string, number: number, x: number, y: number,
          tier: string, priceCents: number, colour: string, iconSvg: string): void {
    const seatType = this.factory.get(tier, priceCents, colour, iconSvg);
    this.seats.set(`${row}${number}`, new Seat(row, number, x, y, seatType));
  }

  sell(row: string, number: number): void {
    const seat = this.seats.get(`${row}${number}`);
    if (seat === undefined) {
      throw new Error(`Unknown seat ${row}${number}`);
    }
    seat.sold = true;
  }

  render(): string[] {
    return Array.from(this.seats.values(), (seat) => seat.render());
  }

  seatCount(): number {
    return this.seats.size;
  }
}

const ICON_STANDARD = "<svg><path d='M2 2h20v20H2z'/></svg>";
const ICON_WHEELCHAIR = "<svg><circle cx='12' cy='12' r='10'/></svg>";

const factory = new SeatTypeFactory();
const seatMap = new SeatMap(factory);

["A", "B", "C"].forEach((row, rowIndex) => {
  for (let number = 1; number <= 4; number++) {
    const x = number * 30;
    const y = rowIndex * 40;
    if (row === "C" && number === 4) {
      seatMap.addSeat(row, number, x, y, "Accessible", 6500, "#43a047", ICON_WHEELCHAIR);
    } else if (row === "A") {
      seatMap.addSeat(row, number, x, y, "Floor", 12000, "#e53935", ICON_STANDARD);
    } else {
      seatMap.addSeat(row, number, x, y, "Balcony", 6500, "#1e88e5", ICON_STANDARD);
    }
  }
});

seatMap.sell("A", 2);
for (const line of seatMap.render().slice(0, 2)) {
  console.log(line);
}
console.log(`${seatMap.seatCount()} seats, ${factory.count()} shared seat types`);
// A1 [Floor $120.00] at (30,0) fill=#e53935
// A2 [Floor $120.00] at (60,0) fill=#9e9e9e
// 12 seats, 3 shared seat types

When to use it

Situations where it pays off.

  • Your program creates a very large number of objects and memory use, not CPU, is the constraint you are hitting.

    Flyweight trades a little indirection for a big reduction in duplicated data. If you only have a few hundred objects, the saving is too small to justify the extra classes.

  • Most of each object's state is repeated across many instances and can be made immutable.

    Sharing only works if the shared part never changes after creation. In SeatLoop, the six seat descriptions are fixed for an event, so they qualify.

  • The varying state can be computed or stored separately and passed into methods.

    The pattern relies on moving extrinsic data out of the flyweight. If every field differs per object, there is nothing to share.

  • Your code does not depend on each object having a distinct identity.

    Flyweights are deliberately shared, so two seats of the same tier return the same SeatType instance. Code that compares types by identity or attaches per-object data to them will break.

How to implement it

Steps to introduce it in existing code.

  1. Measure first. Count the objects and estimate how much of each one is duplicated data; in SeatLoop the SVG icon and strings were the bulk of every Seat.

  2. Split the fields into intrinsic (same across many objects, never changes) and extrinsic (unique per object or changes over time).

  3. Move the intrinsic fields into a flyweight class and make it immutable: readonly properties, frozen dataclasses, no setters.

  4. Change the flyweight's methods so any extrinsic data they need arrives as parameters instead of being read from fields.

  5. Create a factory that caches flyweights by a key built from all intrinsic values, and route every creation through it.

  6. Create a small context class that holds the extrinsic fields plus a reference to its flyweight, and update the client to build contexts through the factory.

  7. Measure again to confirm the saving, and decide whether the cache needs a lifetime policy if new flyweight keys can keep appearing.

Pros and cons

What you gain and what you pay.

Pros

  • Large memory savings when many objects share the same heavy data; SeatLoop goes from 68,000 icon copies to six.
  • Creating a new context is cheap because the expensive part already exists in the cache.
  • The shared state lives in one place, so a change to a seat type's definition between events is made once.
  • Immutable flyweights are safe to share across threads without locking.

Cons

  • Code gets harder to follow: state for one logical seat is split between two classes and passed around as parameters.
  • You may trade memory for CPU if extrinsic state has to be recomputed or looked up on every call.
  • The factory cache can grow without bound if keys are not limited, turning a memory fix into a memory leak.
  • Anyone who mutates a flyweight changes every object that shares it, so immutability has to be enforced, not just assumed.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

What is the difference between intrinsic and extrinsic state?

Intrinsic state is stored inside the flyweight and is the same for every object that shares it, like a seat's tier, price and icon. Extrinsic state depends on the individual object or changes over time, like row, coordinates and sold status. It lives in the context and is passed to the flyweight's methods. A good interview answer names both and explains that only intrinsic state can be shared.

Why must flyweights be immutable?

Because one instance is referenced by many contexts. If code changed the price on the shared Balcony SeatType to mark one seat as discounted, every Balcony seat would show the discount. Per-object differences belong in the context; if a seat needs a different price, it should point to a different flyweight.

Is Flyweight the same as caching?

It uses a cache, but the goal is different. A typical cache avoids recomputing or refetching a result. Flyweight avoids storing duplicate data by guaranteeing that equal intrinsic state maps to one shared object. The factory's cache is the mechanism; deduplication of memory is the purpose.

Do languages already apply this pattern for me?

Some do in specific places. String interning in Java, Python and PHP, and small-integer caching in Python and Java, share immutable values in a flyweight-like way. Those are runtime optimisations for built-in types; for your own domain objects you still have to design the split and the factory yourself.

When should you avoid Flyweight?

When the object count is modest, when most of the state is unique per object, or when the extrinsic state is expensive to recompute on each call. In those cases you add classes and indirection for little or no memory gain. Profile first and apply it only to the object type that dominates memory.

Next guide7 of 7 · Structural patternsProxy Pattern: Control Access with a Stand-In ObjectRead the next one