Flyweight: Share What's the Same

When thousands of objects each carry their own copy of the same few details, memory grows with every object; the Flyweight pattern stores what's the same once per kind and shares it, so each object keeps only what's its own.

Journeyman · OOP · Updated

By

After this lesson you can

  • Share the parts that are the same across many objects, so each object keeps only what's its own
  • Spot the smells that point to Flyweight: thousands of objects carrying identical copies of the same data
  • Tell Flyweight from Singleton and Object Pool by what is shared, and with whom

Key takeaways

  • The smell: thousands of objects carrying identical copies of the same data, so memory grows with the count even though the variety doesn't.
  • The cause: details that belong to a kind of thing (a seat type's price, color and perks) are stored in every thing of that kind.
  • The fix: one shared, read-only object per kind; each object keeps only its own part (row and number) and a reference to its kind.
  • When the kinds are fixed, the modern version is a set of shared constants, such as a Java enum.

Before this: Simple Factory: One Place That Says new, and the idea that two variables can point at the same object.

Harbor Stadium's ticket app shows a seat map: 50,000 seats, each one a standard, premium or accessible seat. Each type has a price (standard $40, premium $90, accessible $40), a color on the map and a list of perks a fan sees when they tap a seat. The map works on phones, but the kiosks at the gates are small tablets, and they keep running out of memory and crashing when the map loads. And next summer the stadium hosts a festival with 200,000 places, on the field and in the stands. By the end of this lesson you'll have met the pattern that keeps a huge map light, Flyweight.

The symptom: 50,000 copies of three things

Here is how the map loads. Each seat comes back from the ticket database with its type's details:

List<Seat> seats = new List<Seat>();
for (int row = 1; row <= 200; row++)
{
    for (int number = 1; number <= 250; number++)
    {
        seats.Add(TicketDatabase.LoadSeat(row, number));
    }
}

Console.WriteLine(quot;Seats: {seats.Count} (standard {seats.Count(seat => seat.Kind == "standard")}, premium {seats.Count(seat => seat.Kind == "premium")}, accessible {seats.Count(seat => seat.Kind == "accessible")})");
Seat picked = seats.First(seat => seat.Row == 12 && seat.Number == 7);
Console.WriteLine(quot;Row 12, seat 7: {picked.Kind}, ${picked.Price}, {picked.Color}, {string.Join(", ", picked.Perks)}");
Console.WriteLine(quot;Perk lists in memory: {seats.Select(seat => seat.Perks).Distinct(ReferenceEqualityComparer.Instance).Count()}");

// Every seat carries its own copy of its type's details.
record Seat(int Row, int Number, string Kind, int Price, string Color, List<string> Perks);

static class TicketDatabase
{
    // Each seat comes back from the database with a fresh copy of its type's details.
    public static Seat LoadSeat(int row, int number)
    {
        string kind = row <= 20 ? "premium" : number <= 2 ? "accessible" : "standard";
        if (kind == "premium") { return new Seat(row, number, kind, 90, "gold", new List<string> { "padded seat", "cup holder", "in-seat service" }); }
        if (kind == "accessible") { return new Seat(row, number, kind, 40, "green", new List<string> { "wheelchair space", "companion seat", "cup holder" }); }
        return new Seat(row, number, kind, 40, "blue", new List<string> { "cup holder" });
    }
}
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 50000
// Every seat carries its own copy of its type's details.
record Seat(int row, int number, String kind, int price, String color, List<String> perks) {}

// Each seat comes back from the database with a fresh copy of its type's details.
Seat loadSeat(int row, int number) {
    String kind = row <= 20 ? "premium" : number <= 2 ? "accessible" : "standard";
    if (kind.equals("premium")) { return new Seat(row, number, kind, 90, "gold", new ArrayList<>(List.of("padded seat", "cup holder", "in-seat service"))); }
    if (kind.equals("accessible")) { return new Seat(row, number, kind, 40, "green", new ArrayList<>(List.of("wheelchair space", "companion seat", "cup holder"))); }
    return new Seat(row, number, kind, 40, "blue", new ArrayList<>(List.of("cup holder")));
}

long count(List<Seat> seats, String kind) {
    return seats.stream().filter(seat -> seat.kind().equals(kind)).count();
}

void main() {
    List<Seat> seats = new ArrayList<>();
    for (int row = 1; row <= 200; row++) {
        for (int number = 1; number <= 250; number++) {
            seats.add(loadSeat(row, number));
        }
    }

    IO.println("Seats: " + seats.size() + " (standard " + count(seats, "standard") + ", premium " + count(seats, "premium") + ", accessible " + count(seats, "accessible") + ")");
    Seat picked = seats.stream().filter(seat -> seat.row() == 12 && seat.number() == 7).findFirst().get();
    IO.println("Row 12, seat 7: " + picked.kind() + ", quot; + picked.price() + ", " + picked.color() + ", " + String.join(", ", picked.perks()));
    Set<List<String>> perkLists = Collections.newSetFromMap(new IdentityHashMap<>());
    for (Seat seat : seats) { perkLists.add(seat.perks()); }
    IO.println("Perk lists in memory: " + perkLists.size());
}
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 50000
class Seat:
    """Every seat carries its own copy of its type's details."""

    def __init__(self, row, number, kind, price, color, perks):
        self.row = row
        self.number = number
        self.kind = kind
        self.price = price
        self.color = color
        self.perks = perks


def load_seat(row, number):
    """Each seat comes back from the database with a fresh copy of its type's details."""
    kind = "premium" if row <= 20 else "accessible" if number <= 2 else "standard"
    if kind == "premium":
        return Seat(row, number, kind, 90, "gold", ["padded seat", "cup holder", "in-seat service"])
    if kind == "accessible":
        return Seat(row, number, kind, 40, "green", ["wheelchair space", "companion seat", "cup holder"])
    return Seat(row, number, kind, 40, "blue", ["cup holder"])


seats = [load_seat(row, number) for row in range(1, 201) for number in range(1, 251)]


def count(kind):
    return sum(1 for seat in seats if seat.kind == kind)


print(f"Seats: {len(seats)} (standard {count('standard')}, premium {count('premium')}, accessible {count('accessible')})")
picked = next(seat for seat in seats if seat.row == 12 and seat.number == 7)
print(f"Row 12, seat 7: {picked.kind}, ${picked.price}, {picked.color}, {', '.join(picked.perks)}")
print(f"Perk lists in memory: {len({id(seat.perks) for seat in seats})}")
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 50000
// Every seat carries its own copy of its type's details.
class Seat {
  constructor(row, number, kind, price, color, perks) {
    this.row = row;
    this.number = number;
    this.kind = kind;
    this.price = price;
    this.color = color;
    this.perks = perks;
  }
}

// Each seat comes back from the database with a fresh copy of its type's details.
function loadSeat(row, number) {
  const kind = row <= 20 ? "premium" : number <= 2 ? "accessible" : "standard";
  if (kind === "premium") { return new Seat(row, number, kind, 90, "gold", ["padded seat", "cup holder", "in-seat service"]); }
  if (kind === "accessible") { return new Seat(row, number, kind, 40, "green", ["wheelchair space", "companion seat", "cup holder"]); }
  return new Seat(row, number, kind, 40, "blue", ["cup holder"]);
}

const seats = [];
for (let row = 1; row <= 200; row++) {
  for (let number = 1; number <= 250; number++) {
    seats.push(loadSeat(row, number));
  }
}

const count = (kind) => seats.filter((seat) => seat.kind === kind).length;
console.log(`Seats: ${seats.length} (standard ${count("standard")}, premium ${count("premium")}, accessible ${count("accessible")})`);
const picked = seats.find((seat) => seat.row === 12 && seat.number === 7);
console.log(`Row 12, seat 7: ${picked.kind}, ${picked.price}, ${picked.color}, ${picked.perks.join(", ")}`);
console.log(`Perk lists in memory: ${new Set(seats.map((seat) => seat.perks)).size}`);
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 50000
// Every seat carries its own copy of its type's details.
class Seat {
  row: number;
  number: number;
  kind: string;
  price: number;
  color: string;
  perks: string[];

  constructor(row: number, number: number, kind: string, price: number, color: string, perks: string[]) {
    this.row = row;
    this.number = number;
    this.kind = kind;
    this.price = price;
    this.color = color;
    this.perks = perks;
  }
}

// Each seat comes back from the database with a fresh copy of its type's details.
function loadSeat(row: number, number: number): Seat {
  const kind = row <= 20 ? "premium" : number <= 2 ? "accessible" : "standard";
  if (kind === "premium") { return new Seat(row, number, kind, 90, "gold", ["padded seat", "cup holder", "in-seat service"]); }
  if (kind === "accessible") { return new Seat(row, number, kind, 40, "green", ["wheelchair space", "companion seat", "cup holder"]); }
  return new Seat(row, number, kind, 40, "blue", ["cup holder"]);
}

const seats: Seat[] = [];
for (let row = 1; row <= 200; row++) {
  for (let number = 1; number <= 250; number++) {
    seats.push(loadSeat(row, number));
  }
}

const countKind = (kind: string): number => seats.filter((seat) => seat.kind === kind).length;
console.log(`Seats: ${seats.length} (standard ${countKind("standard")}, premium ${countKind("premium")}, accessible ${countKind("accessible")})`);
const picked = seats.find((seat) => seat.row === 12 && seat.number === 7)!;
console.log(`Row 12, seat 7: ${picked.kind}, ${picked.price}, ${picked.color}, ${picked.perks.join(", ")}`);
console.log(`Perk lists in memory: ${new Set(seats.map((seat) => seat.perks)).size}`);
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 50000

There are only three kinds of seat, but the last line counts 50,000 perk lists in memory. Every premium seat carries its own list saying "padded seat, cup holder, in-seat service", and its own price and color. The map's memory grows with the number of seats, even though the number of different things in it never goes past three. At 200,000 places, it's four times worse.

Read it as a doctor would:

  • The symptom: thousands of objects carrying identical copies of the same data, so memory grows with how many there are.
  • The cause: details that belong to a kind of seat (its price, color and perks) are stored in every seat of that kind.
  • The cure: coming up, once we've tried the obvious fixes.

What would you try?

Store less. Drop the perks and keep only the price. The map gets lighter, and fans can't see what a premium seat comes with.

Load seats only when they're on the screen. It helps the first screen, but the zoomed-out view of the whole stadium still makes all 50,000.

Give each seat only its type's name, and look the details up in one table. This one works: the details are stored once. It's nearly the fix. What it's missing is one place in charge of the table, so nobody builds a second copy, and a promise that nobody changes a detail that 5,000 seats share.

What we want: each seat keeps only what's truly its own, its row and number, and everything that's the same for its type is stored once and shared by every seat of that type.

The everyday version: paint by numbers

A paint-by-numbers canvas has hundreds of small regions, and each region holds only a number, such as 3. The colors aren't written into the regions; they're in the key at the bottom, once each: 3 is sky blue. A region knows where it is and which number it has, and the key knows what the number looks like. That's also why nobody changes the key halfway through: every region numbered 3 would change with it.

A paint-by-numbers canvas of a mountain lake, its regions outlined and each holding only a small number, 1, 2 or 3, with a color key below it that shows each number's color once: 1 dark green, 2 gray, 3 sky blue

The fix: store what's the same once, and share it

The fix in one sentence: split each object's data in two; the part that's the same for a whole kind goes into one shared object per kind, which never changes, and each object keeps only its own part and a reference to the shared one.

Flyweight's roles: the seat map asks the flyweight factory for a seat type by name; it makes each kind once (standard $40 blue, premium $90 gold, accessible $40 green) and hands out the same one. The 50,000 seats keep only a row and number, each pointing to its shared type

List<Seat> seats = new List<Seat>();
for (int row = 1; row <= 200; row++)
{
    for (int number = 1; number <= 250; number++)
    {
        string kind = row <= 20 ? "premium" : number <= 2 ? "accessible" : "standard";
        seats.Add(new Seat(row, number, SeatTypes.Get(kind)));
    }
}

Console.WriteLine(quot;Seats: {seats.Count} (standard {seats.Count(seat => seat.Type.Kind == "standard")}, premium {seats.Count(seat => seat.Type.Kind == "premium")}, accessible {seats.Count(seat => seat.Type.Kind == "accessible")})");
Seat picked = seats.First(seat => seat.Row == 12 && seat.Number == 7);
Console.WriteLine(quot;Row 12, seat 7: {picked.Type.Kind}, ${picked.Type.Price}, {picked.Type.Color}, {string.Join(", ", picked.Type.Perks)}");
Console.WriteLine(quot;Perk lists in memory: {seats.Select(seat => seat.Type.Perks).Distinct(ReferenceEqualityComparer.Instance).Count()}");

// Only what belongs to this one seat: its row and number. The rest is shared.
record Seat(int Row, int Number, SeatType Type);

// The shared part: one object per kind of seat. It never changes, so sharing it is safe.
record SeatType(string Kind, int Price, string Color, IReadOnlyList<string> Perks);

// The one place that hands out seat types: it makes each one once, then hands out the same one.
static class SeatTypes
{
    private static readonly Dictionary<string, SeatType> made = new Dictionary<string, SeatType>();

    public static SeatType Get(string kind)
    {
        if (!made.ContainsKey(kind))
        {
            made[kind] = TicketDatabase.LoadType(kind);
        }
        return made[kind];
    }
}

static class TicketDatabase
{
    public static SeatType LoadType(string kind)
    {
        if (kind == "premium") { return new SeatType(kind, 90, "gold", new List<string> { "padded seat", "cup holder", "in-seat service" }); }
        if (kind == "accessible") { return new SeatType(kind, 40, "green", new List<string> { "wheelchair space", "companion seat", "cup holder" }); }
        return new SeatType(kind, 40, "blue", new List<string> { "cup holder" });
    }
}
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 3
// Only what belongs to this one seat: its row and number. The rest is shared.
record Seat(int row, int number, SeatType type) {}

// The shared part: one object per kind of seat. It never changes, so sharing it is safe.
record SeatType(String kind, int price, String color, List<String> perks) {}

SeatType loadType(String kind) {
    if (kind.equals("premium")) { return new SeatType(kind, 90, "gold", List.of("padded seat", "cup holder", "in-seat service")); }
    if (kind.equals("accessible")) { return new SeatType(kind, 40, "green", List.of("wheelchair space", "companion seat", "cup holder")); }
    return new SeatType(kind, 40, "blue", List.of("cup holder"));
}

// The one place that hands out seat types: it makes each one once, then hands out the same one.
Map<String, SeatType> made = new HashMap<>();

SeatType seatType(String kind) {
    return made.computeIfAbsent(kind, this::loadType);
}

long count(List<Seat> seats, String kind) {
    return seats.stream().filter(seat -> seat.type().kind().equals(kind)).count();
}

void main() {
    List<Seat> seats = new ArrayList<>();
    for (int row = 1; row <= 200; row++) {
        for (int number = 1; number <= 250; number++) {
            String kind = row <= 20 ? "premium" : number <= 2 ? "accessible" : "standard";
            seats.add(new Seat(row, number, seatType(kind)));
        }
    }

    IO.println("Seats: " + seats.size() + " (standard " + count(seats, "standard") + ", premium " + count(seats, "premium") + ", accessible " + count(seats, "accessible") + ")");
    Seat picked = seats.stream().filter(seat -> seat.row() == 12 && seat.number() == 7).findFirst().get();
    IO.println("Row 12, seat 7: " + picked.type().kind() + ", quot; + picked.type().price() + ", " + picked.type().color() + ", " + String.join(", ", picked.type().perks()));
    Set<List<String>> perkLists = Collections.newSetFromMap(new IdentityHashMap<>());
    for (Seat seat : seats) { perkLists.add(seat.type().perks()); }
    IO.println("Perk lists in memory: " + perkLists.size());
}
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 3
class SeatType:
    """The shared part: one object per kind of seat. It never changes, so sharing it is safe."""

    def __init__(self, kind, price, color, perks):
        self.kind = kind
        self.price = price
        self.color = color
        self.perks = tuple(perks)


class Seat:
    """Only what belongs to this one seat: its row and number. The rest is shared."""

    def __init__(self, row, number, seat_type):
        self.row = row
        self.number = number
        self.type = seat_type


def load_type(kind):
    if kind == "premium":
        return SeatType(kind, 90, "gold", ["padded seat", "cup holder", "in-seat service"])
    if kind == "accessible":
        return SeatType(kind, 40, "green", ["wheelchair space", "companion seat", "cup holder"])
    return SeatType(kind, 40, "blue", ["cup holder"])


made = {}


def seat_type(kind):
    """The one place that hands out seat types: it makes each one once, then hands out the same one."""
    if kind not in made:
        made[kind] = load_type(kind)
    return made[kind]


seats = []
for row in range(1, 201):
    for number in range(1, 251):
        kind = "premium" if row <= 20 else "accessible" if number <= 2 else "standard"
        seats.append(Seat(row, number, seat_type(kind)))


def count(kind):
    return sum(1 for seat in seats if seat.type.kind == kind)


print(f"Seats: {len(seats)} (standard {count('standard')}, premium {count('premium')}, accessible {count('accessible')})")
picked = next(seat for seat in seats if seat.row == 12 and seat.number == 7)
print(f"Row 12, seat 7: {picked.type.kind}, ${picked.type.price}, {picked.type.color}, {', '.join(picked.type.perks)}")
print(f"Perk lists in memory: {len({id(seat.type.perks) for seat in seats})}")
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 3
// The shared part: one object per kind of seat. It never changes, so sharing it is safe.
class SeatType {
  constructor(kind, price, color, perks) {
    this.kind = kind;
    this.price = price;
    this.color = color;
    this.perks = Object.freeze(perks);
    Object.freeze(this);
  }
}

// Only what belongs to this one seat: its row and number. The rest is shared.
class Seat {
  constructor(row, number, type) {
    this.row = row;
    this.number = number;
    this.type = type;
  }
}

function loadType(kind) {
  if (kind === "premium") { return new SeatType(kind, 90, "gold", ["padded seat", "cup holder", "in-seat service"]); }
  if (kind === "accessible") { return new SeatType(kind, 40, "green", ["wheelchair space", "companion seat", "cup holder"]); }
  return new SeatType(kind, 40, "blue", ["cup holder"]);
}

// The one place that hands out seat types: it makes each one once, then hands out the same one.
const made = new Map();
function seatType(kind) {
  if (!made.has(kind)) { made.set(kind, loadType(kind)); }
  return made.get(kind);
}

const seats = [];
for (let row = 1; row <= 200; row++) {
  for (let number = 1; number <= 250; number++) {
    const kind = row <= 20 ? "premium" : number <= 2 ? "accessible" : "standard";
    seats.push(new Seat(row, number, seatType(kind)));
  }
}

const count = (kind) => seats.filter((seat) => seat.type.kind === kind).length;
console.log(`Seats: ${seats.length} (standard ${count("standard")}, premium ${count("premium")}, accessible ${count("accessible")})`);
const picked = seats.find((seat) => seat.row === 12 && seat.number === 7);
console.log(`Row 12, seat 7: ${picked.type.kind}, ${picked.type.price}, ${picked.type.color}, ${picked.type.perks.join(", ")}`);
console.log(`Perk lists in memory: ${new Set(seats.map((seat) => seat.type.perks)).size}`);
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 3
// The shared part: one object per kind of seat. It never changes, so sharing it is safe.
class SeatType {
  readonly kind: string;
  readonly price: number;
  readonly color: string;
  readonly perks: readonly string[];

  constructor(kind: string, price: number, color: string, perks: string[]) {
    this.kind = kind;
    this.price = price;
    this.color = color;
    this.perks = Object.freeze(perks);
  }
}

// Only what belongs to this one seat: its row and number. The rest is shared.
class Seat {
  row: number;
  number: number;
  type: SeatType;

  constructor(row: number, number: number, type: SeatType) {
    this.row = row;
    this.number = number;
    this.type = type;
  }
}

function loadType(kind: string): SeatType {
  if (kind === "premium") { return new SeatType(kind, 90, "gold", ["padded seat", "cup holder", "in-seat service"]); }
  if (kind === "accessible") { return new SeatType(kind, 40, "green", ["wheelchair space", "companion seat", "cup holder"]); }
  return new SeatType(kind, 40, "blue", ["cup holder"]);
}

// The one place that hands out seat types: it makes each one once, then hands out the same one.
const made = new Map<string, SeatType>();
function seatType(kind: string): SeatType {
  if (!made.has(kind)) { made.set(kind, loadType(kind)); }
  return made.get(kind)!;
}

const seats: Seat[] = [];
for (let row = 1; row <= 200; row++) {
  for (let number = 1; number <= 250; number++) {
    const kind = row <= 20 ? "premium" : number <= 2 ? "accessible" : "standard";
    seats.push(new Seat(row, number, seatType(kind)));
  }
}

const countKind = (kind: string): number => seats.filter((seat) => seat.type.kind === kind).length;
console.log(`Seats: ${seats.length} (standard ${countKind("standard")}, premium ${countKind("premium")}, accessible ${countKind("accessible")})`);
const picked = seats.find((seat) => seat.row === 12 && seat.number === 7)!;
console.log(`Row 12, seat 7: ${picked.type.kind}, ${picked.type.price}, ${picked.type.color}, ${picked.type.perks.join(", ")}`);
console.log(`Perk lists in memory: ${new Set(seats.map((seat) => seat.type.perks)).size}`);
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 3

The same lines, except the last: 3 perk lists in memory, one for each kind of seat. Each seat now holds two numbers and one reference, and every premium seat points to the same premium SeatType. SeatTypes.Get (seatType in the other languages) is the one place that hands out seat types, a factory like Pass 1's: it makes each kind the first time it's asked for, and hands out that same object every time after.

The shared part must never change. If anyone could change the price through one premium seat, all 5,000 premium seats would change with it. So SeatType is read-only: a record in C# and Java, with its perks in a tuple in Python, frozen in JavaScript and marked readonly in TypeScript.

The seat map's memory, before and after. Before: every seat carries its own copy of its row, number, price, color and perks, so 50,000 seats hold 50,000 perk lists. After: each seat keeps only its row and number and points to one of three shared seat types: 3 perk lists

How it got its name

Teams writing text editors and games kept meeting this problem: a document with a million letters, a forest with ten thousand trees, each one mostly the same as the next. They kept landing on the same fix, and the 1994 book of patterns named it the Flyweight pattern, after the lightest weight class in boxing: each object becomes very light, because the heavy part is shared.

In your textbook, the shared part is the intrinsic state: it belongs to the kind, wherever the object is (a premium seat's price, color and perks). Each object's own part is the extrinsic state: it comes from outside the shared object (this seat's row and number). And the shared object is an immutable object: once it's made, it can't be changed.

The modern version: a fixed set of shared constants

When every kind is known while you write the code, you don't need a factory to make them on demand. Make each kind once, as a constant:

List<Seat> seats = new List<Seat>();
for (int row = 1; row <= 200; row++)
{
    for (int number = 1; number <= 250; number++)
    {
        seats.Add(new Seat(row, number, row <= 20 ? SeatType.Premium : number <= 2 ? SeatType.Accessible : SeatType.Standard));
    }
}

Console.WriteLine(quot;Seats: {seats.Count} (standard {seats.Count(seat => seat.Type == SeatType.Standard)}, premium {seats.Count(seat => seat.Type == SeatType.Premium)}, accessible {seats.Count(seat => seat.Type == SeatType.Accessible)})");
Seat picked = seats.First(seat => seat.Row == 12 && seat.Number == 7);
Console.WriteLine(quot;Row 12, seat 7: {picked.Type.Kind}, ${picked.Type.Price}, {picked.Type.Color}, {string.Join(", ", picked.Type.Perks)}");
Console.WriteLine(quot;Perk lists in memory: {seats.Select(seat => seat.Type.Perks).Distinct(ReferenceEqualityComparer.Instance).Count()}");

record Seat(int Row, int Number, SeatType Type);

// The kinds are fixed, so each is one shared, read-only object, made once when the program starts.
record SeatType(string Kind, int Price, string Color, IReadOnlyList<string> Perks)
{
    public static readonly SeatType Standard = new SeatType("standard", 40, "blue", new[] { "cup holder" });
    public static readonly SeatType Premium = new SeatType("premium", 90, "gold", new[] { "padded seat", "cup holder", "in-seat service" });
    public static readonly SeatType Accessible = new SeatType("accessible", 40, "green", new[] { "wheelchair space", "companion seat", "cup holder" });
}
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 3
record Seat(int row, int number, SeatType type) {}

// The kinds are fixed, so each is one shared, read-only object: an enum makes exactly one of each.
enum SeatType {
    STANDARD(40, "blue", List.of("cup holder")),
    PREMIUM(90, "gold", List.of("padded seat", "cup holder", "in-seat service")),
    ACCESSIBLE(40, "green", List.of("wheelchair space", "companion seat", "cup holder"));

    final int price;
    final String color;
    final List<String> perks;

    SeatType(int price, String color, List<String> perks) {
        this.price = price;
        this.color = color;
        this.perks = perks;
    }

    String kind() { return name().toLowerCase(); }
}

long count(List<Seat> seats, SeatType type) {
    return seats.stream().filter(seat -> seat.type() == type).count();
}

void main() {
    List<Seat> seats = new ArrayList<>();
    for (int row = 1; row <= 200; row++) {
        for (int number = 1; number <= 250; number++) {
            seats.add(new Seat(row, number, row <= 20 ? SeatType.PREMIUM : number <= 2 ? SeatType.ACCESSIBLE : SeatType.STANDARD));
        }
    }

    IO.println("Seats: " + seats.size() + " (standard " + count(seats, SeatType.STANDARD) + ", premium " + count(seats, SeatType.PREMIUM) + ", accessible " + count(seats, SeatType.ACCESSIBLE) + ")");
    Seat picked = seats.stream().filter(seat -> seat.row() == 12 && seat.number() == 7).findFirst().get();
    IO.println("Row 12, seat 7: " + picked.type().kind() + ", quot; + picked.type().price + ", " + picked.type().color + ", " + String.join(", ", picked.type().perks));
    Set<List<String>> perkLists = Collections.newSetFromMap(new IdentityHashMap<>());
    for (Seat seat : seats) { perkLists.add(seat.type().perks); }
    IO.println("Perk lists in memory: " + perkLists.size());
}
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 3
from dataclasses import dataclass


@dataclass(frozen=True)
class SeatType:
    """A frozen dataclass can't be changed after it's made, so sharing it is safe."""
    kind: str
    price: int
    color: str
    perks: tuple


# The kinds are fixed, so each is one shared object, made once when the module loads.
STANDARD = SeatType("standard", 40, "blue", ("cup holder",))
PREMIUM = SeatType("premium", 90, "gold", ("padded seat", "cup holder", "in-seat service"))
ACCESSIBLE = SeatType("accessible", 40, "green", ("wheelchair space", "companion seat", "cup holder"))


@dataclass
class Seat:
    row: int
    number: int
    type: SeatType


seats = [Seat(row, number, PREMIUM if row <= 20 else ACCESSIBLE if number <= 2 else STANDARD)
         for row in range(1, 201) for number in range(1, 251)]


def count(seat_type):
    return sum(1 for seat in seats if seat.type is seat_type)


print(f"Seats: {len(seats)} (standard {count(STANDARD)}, premium {count(PREMIUM)}, accessible {count(ACCESSIBLE)})")
picked = next(seat for seat in seats if seat.row == 12 and seat.number == 7)
print(f"Row 12, seat 7: {picked.type.kind}, ${picked.type.price}, {picked.type.color}, {', '.join(picked.type.perks)}")
print(f"Perk lists in memory: {len({id(seat.type.perks) for seat in seats})}")
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 3
// The kinds are fixed, so each is one shared object, frozen so nobody can change it.
const SeatTypes = Object.freeze({
  standard: Object.freeze({ kind: "standard", price: 40, color: "blue", perks: Object.freeze(["cup holder"]) }),
  premium: Object.freeze({ kind: "premium", price: 90, color: "gold", perks: Object.freeze(["padded seat", "cup holder", "in-seat service"]) }),
  accessible: Object.freeze({ kind: "accessible", price: 40, color: "green", perks: Object.freeze(["wheelchair space", "companion seat", "cup holder"]) }),
});

const seats = [];
for (let row = 1; row <= 200; row++) {
  for (let number = 1; number <= 250; number++) {
    const type = row <= 20 ? SeatTypes.premium : number <= 2 ? SeatTypes.accessible : SeatTypes.standard;
    seats.push({ row, number, type });
  }
}

const count = (type) => seats.filter((seat) => seat.type === type).length;
console.log(`Seats: ${seats.length} (standard ${count(SeatTypes.standard)}, premium ${count(SeatTypes.premium)}, accessible ${count(SeatTypes.accessible)})`);
const picked = seats.find((seat) => seat.row === 12 && seat.number === 7);
console.log(`Row 12, seat 7: ${picked.type.kind}, ${picked.type.price}, ${picked.type.color}, ${picked.type.perks.join(", ")}`);
console.log(`Perk lists in memory: ${new Set(seats.map((seat) => seat.type.perks)).size}`);
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 3
// The kinds are fixed, so each is one shared object, frozen so nobody can change it.
const SeatTypes = Object.freeze({
  standard: Object.freeze({ kind: "standard", price: 40, color: "blue", perks: Object.freeze(["cup holder"]) }),
  premium: Object.freeze({ kind: "premium", price: 90, color: "gold", perks: Object.freeze(["padded seat", "cup holder", "in-seat service"]) }),
  accessible: Object.freeze({ kind: "accessible", price: 40, color: "green", perks: Object.freeze(["wheelchair space", "companion seat", "cup holder"]) }),
});

type SeatType = (typeof SeatTypes)[keyof typeof SeatTypes];

interface Seat {
  row: number;
  number: number;
  type: SeatType;
}

const seats: Seat[] = [];
for (let row = 1; row <= 200; row++) {
  for (let number = 1; number <= 250; number++) {
    const type = row <= 20 ? SeatTypes.premium : number <= 2 ? SeatTypes.accessible : SeatTypes.standard;
    seats.push({ row, number, type });
  }
}

const countType = (type: SeatType): number => seats.filter((seat) => seat.type === type).length;
console.log(`Seats: ${seats.length} (standard ${countType(SeatTypes.standard)}, premium ${countType(SeatTypes.premium)}, accessible ${countType(SeatTypes.accessible)})`);
const picked = seats.find((seat) => seat.row === 12 && seat.number === 7)!;
console.log(`Row 12, seat 7: ${picked.type.kind}, ${picked.type.price}, ${picked.type.color}, ${picked.type.perks.join(", ")}`);
console.log(`Perk lists in memory: ${new Set(seats.map((seat) => seat.type.perks)).size}`);
Seats: 50000 (standard 44640, premium 5000, accessible 360)
Row 12, seat 7: premium, $90, gold, padded seat, cup holder, in-seat service
Perk lists in memory: 3

Java's enum makes exactly one object for each value, so an enum with fields is a flyweight, built into the language. C# uses static readonly instances of a record, Python a frozen dataclass, and JavaScript and TypeScript frozen objects. The factory version is still the one to use when the kinds come from outside the code, such as seat types loaded from the ticket database.

Where you've already used it

  • Strings: C# and Java keep one copy of each string literal in a program, and Python shares short strings and small numbers.
  • Java's Integer.valueOf(42) hands back a shared object for every number from -128 to 127.
  • Fonts: a text editor draws every letter "e" from one shared shape, and each "e" on the page is only a position.
  • Games draw a forest of thousands of trees from one shared tree model; each tree keeps only where it stands and how tall it is.

Flyweight and its look-alikes

A Singleton (Singleton: Only One, Ever) is one object for the whole app; a flyweight is one shared object per kind, here three. An object pool, in the next lesson, shares expensive objects too, but lends each one to one user at a time and takes it back; a flyweight is used by everyone at once and never given back.

When not to use it

  • When there aren't many objects. A 200-seat theater doesn't need it: the copies cost almost nothing.
  • When the "shared" part isn't really the same. If some premium seats get their own price for a special game, the price belongs to the seat, not the kind.
  • When memory isn't the problem. It adds a factory or a set of constants, read-only rules, and one more step to read a seat's price.

How often you'll meet it: rarely in app code, and all the time underneath it (our estimate: runtimes, editors and games use it constantly; app code needs it only for very many similar objects).

Check yourself

2 questions to try on the lesson page.

So what

When thousands of objects carry the same few details, store each detail once per kind and share it, read-only. The count of objects can grow; the memory for what they have in common doesn't.

Key terms

Cheat sheets