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.
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 entriesThe 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 typesfrom dataclasses import dataclass
@dataclass(frozen=True)
class SeatType:
tier: str
price_cents: int
colour: str
icon_svg: str
def render(self, row: str, number: int, x: int, y: int, sold: bool) -> str:
fill = "#9e9e9e" if sold else self.colour
price = f"{self.price_cents / 100:.2f}"
return f"{row}{number} [{self.tier} ${price}] at ({x},{y}) fill={fill}"
class SeatTypeFactory:
def __init__(self) -> None:
self._cache: dict[str, SeatType] = {}
def get(self, tier: str, price_cents: int, colour: str, icon_svg: str) -> SeatType:
key = f"{tier}|{price_cents}|{colour}|{icon_svg}"
if key not in self._cache:
self._cache[key] = SeatType(tier, price_cents, colour, icon_svg)
return self._cache[key]
def count(self) -> int:
return len(self._cache)
class Seat:
def __init__(self, row: str, number: int, x: int, y: int, seat_type: SeatType) -> None:
self.row = row
self.number = number
self.x = x
self.y = y
self.seat_type = seat_type
self.sold = False
def render(self) -> str:
return self.seat_type.render(self.row, self.number, self.x, self.y, self.sold)
class SeatMap:
def __init__(self, factory: SeatTypeFactory) -> None:
self._factory = factory
self._seats: dict[str, Seat] = {}
def add_seat(self, row: str, number: int, x: int, y: int,
tier: str, price_cents: int, colour: str, icon_svg: str) -> None:
seat_type = self._factory.get(tier, price_cents, colour, icon_svg)
self._seats[f"{row}{number}"] = Seat(row, number, x, y, seat_type)
def sell(self, row: str, number: int) -> None:
seat = self._seats.get(f"{row}{number}")
if seat is None:
raise ValueError(f"Unknown seat {row}{number}")
seat.sold = True
def render(self) -> list[str]:
return [seat.render() for seat in self._seats.values()]
def seat_count(self) -> int:
return len(self._seats)
ICON_STANDARD = "<svg><path d='M2 2h20v20H2z'/></svg>"
ICON_WHEELCHAIR = "<svg><circle cx='12' cy='12' r='10'/></svg>"
factory = SeatTypeFactory()
seat_map = SeatMap(factory)
for row_index, row in enumerate(["A", "B", "C"]):
for number in range(1, 5):
x = number * 30
y = row_index * 40
if row == "C" and number == 4:
seat_map.add_seat(row, number, x, y, "Accessible", 6500, "#43a047", ICON_WHEELCHAIR)
elif row == "A":
seat_map.add_seat(row, number, x, y, "Floor", 12000, "#e53935", ICON_STANDARD)
else:
seat_map.add_seat(row, number, x, y, "Balcony", 6500, "#1e88e5", ICON_STANDARD)
seat_map.sell("A", 2)
for line in seat_map.render()[:2]:
print(line)
print(f"{seat_map.seat_count()} 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<?php
final class SeatType
{
public function __construct(
public readonly string $tier,
public readonly int $priceCents,
public readonly string $colour,
public readonly string $iconSvg,
) {}
public function render(string $row, int $number, int $x, int $y, bool $sold): string
{
$fill = $sold ? '#9e9e9e' : $this->colour;
$price = number_format($this->priceCents / 100, 2);
return sprintf('%s%d [%s $%s] at (%d,%d) fill=%s', $row, $number, $this->tier, $price, $x, $y, $fill);
}
}
final class SeatTypeFactory
{
/** @var array<string, SeatType> */
private array $cache = [];
public function get(string $tier, int $priceCents, string $colour, string $iconSvg): SeatType
{
$key = "{$tier}|{$priceCents}|{$colour}|{$iconSvg}";
if (!isset($this->cache[$key])) {
$this->cache[$key] = new SeatType($tier, $priceCents, $colour, $iconSvg);
}
return $this->cache[$key];
}
public function count(): int
{
return count($this->cache);
}
}
final class Seat
{
public bool $sold = false;
public function __construct(
public readonly string $row,
public readonly int $number,
public readonly int $x,
public readonly int $y,
public readonly SeatType $seatType,
) {}
public function render(): string
{
return $this->seatType->render($this->row, $this->number, $this->x, $this->y, $this->sold);
}
}
final class SeatMap
{
/** @var array<string, Seat> */
private array $seats = [];
public function __construct(private readonly SeatTypeFactory $factory) {}
public function addSeat(string $row, int $number, int $x, int $y,
string $tier, int $priceCents, string $colour, string $iconSvg): void
{
$seatType = $this->factory->get($tier, $priceCents, $colour, $iconSvg);
$this->seats[$row . $number] = new Seat($row, $number, $x, $y, $seatType);
}
public function sell(string $row, int $number): void
{
if (!isset($this->seats[$row . $number])) {
throw new InvalidArgumentException("Unknown seat {$row}{$number}");
}
$this->seats[$row . $number]->sold = true;
}
/** @return string[] */
public function render(): array
{
return array_map(fn (Seat $seat): string => $seat->render(), array_values($this->seats));
}
public function seatCount(): int
{
return count($this->seats);
}
}
const ICON_STANDARD = "<svg><path d='M2 2h20v20H2z'/></svg>";
const ICON_WHEELCHAIR = "<svg><circle cx='12' cy='12' r='10'/></svg>";
$factory = new SeatTypeFactory();
$seatMap = new SeatMap($factory);
foreach (['A', 'B', 'C'] as $rowIndex => $row) {
for ($number = 1; $number <= 4; $number++) {
$x = $number * 30;
$y = $rowIndex * 40;
if ($row === 'C' && $number === 4) {
$seatMap->addSeat($row, $number, $x, $y, 'Accessible', 6500, '#43a047', ICON_WHEELCHAIR);
} elseif ($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);
foreach (array_slice($seatMap->render(), 0, 2) as $line) {
echo $line . PHP_EOL;
}
echo $seatMap->seatCount() . ' seats, ' . $factory->count() . ' shared seat types' . PHP_EOL;
// A1 [Floor $120.00] at (30,0) fill=#e53935
// A2 [Floor $120.00] at (60,0) fill=#9e9e9e
// 12 seats, 3 shared seat typesWhen 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.
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.
Split the fields into intrinsic (same across many objects, never changes) and extrinsic (unique per object or changes over time).
Move the intrinsic fields into a flyweight class and make it immutable: readonly properties, frozen dataclasses, no setters.
Change the flyweight's methods so any extrinsic data they need arrives as parameters instead of being read from fields.
Create a factory that caches flyweights by a key built from all intrinsic values, and route every creation through it.
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.
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.
- Composite Pattern: Treat Single Items and Groups Through One Interface
Composite trees often have many identical leaves. Making those leaves flyweights keeps a large tree cheap, though the leaves can then no longer store a reference to their parent.
- Singleton: One Shared Instance, and Why You Usually Want DI Instead
A flyweight factory looks a bit like a Singleton with many instances. The difference is that Singleton guarantees one instance of a class, while Flyweight keeps one instance per distinct intrinsic state, and those instances are immutable.
- State Pattern: Explicit State Machines Without the Switch Statements
State objects that hold no per-context data can be shared as flyweights, so thousands of contexts in the same state point to one state object.
- Strategy: swap the rule without touching who uses it
Stateless strategies are natural flyweights: one instance can serve every client that needs that behaviour.
- Proxy Pattern: Control Access with a Stand-In Object
Both put an object in front of a client, but Proxy controls access to one real object, while Flyweight is about sharing one object across many clients to save memory.
- Duplicate Code: When the Same Logic Lives in Several Places
Flyweight fixes duplicated data at runtime rather than duplicated source code, but the instinct is the same: keep one copy of what repeats.
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.