Article · Flyweight · Composite
Flyweight – how to fit 60,000 stadium seats in memory
Flyweight separates the state shared by many objects from the state unique to each one, and shares the former. A stadium seat map example from a ticket booking system in C#, TypeScript, Java, Go and Python.
Most GoF patterns are about readable, flexible code. Flyweight is the exception – it is an optimisation pattern. When you have hundreds of thousands of similar objects that differ in only a few fields, Flyweight pulls the common part out into a single shared instance and leaves only what is truly unique in each object.
The problem: a stadium map that eats memory
A ticket booking system shows an interactive stadium map: 60,000 seats, each with a category (VIP, standard, accessible), a price, a colour and an SVG icon used for drawing. The first version of the model was simple:
class Seat {
constructor(
public row: number,
public number: number,
public category: string, // the same 6 values repeated 60 000 times
public price: number,
public color: string,
public iconSvg: string, // ~2 KB of path data, copied into every seat
) {}
}The icon is about 2 KB of path data, repeated in each of the 60 thousand seats. A server that caches the maps of several events at once starts to choke, and the app in a phone browser stutters when scrolling.
| Copies in every seat | Flyweight | |
|---|---|---|
| Hall, 5,000 seats | 10.4 MB | 0.25 MB |
| Arena, 20,000 seats | 41.8 MB | 0.97 MB |
| Stadium, 60,000 seats | 125.3 MB | 2.89 MB |
The solution: share what repeats
We notice that a stadium has only a handful of seat types but thousands of seats. Category, price, colour and icon belong to the type – that is intrinsic state. Row and number belong to a specific seat – that is extrinsic state. We extract an immutable SeatType class, and Seat stores only the row, the number and a reference to its type. A SeatTypeFactory returns an existing type instead of creating a new one.
| State | Example | Where it lives | How many copies |
|---|---|---|---|
| Intrinsic | category, price, colour, icon | SeatType (the flyweight) | one per type – here 2 |
| Extrinsic | row, number, booking status | Seat (the context) | one per seat – 60,000 |
| Role | In the example | Responsibility |
|---|---|---|
| Flyweight | SeatType | immutable, shared intrinsic state |
| Flyweight factory | SeatTypeFactory | returns an existing instance or creates it once |
| Context | Seat | extrinsic state + a reference to the flyweight |
| Client | the map view | creates seats through the factory, supplies extrinsic state |
Implementation in five languages
Each example creates 60,000 seats, and at the end the factory reports that only two types exist. In C# Seat is a struct (readonly record struct), so the seats are not even separate heap objects; in Python slots=True removes the attribute dictionary from every instance.
SeatTypeFactory
var factory = new SeatTypeFactory();
var seats = new List<Seat>(capacity: 60_000);
for (var row = 1; row <= 200; row++)
for (var number = 1; number <= 300; number++)
seats.Add(new Seat(row, number, factory.Get(row <= 20 ? "VIP" : "Standard")));
Console.WriteLine($"{seats.Count} seats, {factory.Count} shared seat types");
Console.WriteLine(seats[0].Describe());
// Flyweight: intrinsic, immutable state shared by thousands of seats.
public sealed record SeatType(string Category, decimal Price, string Color, string IconSvg);
// Context: extrinsic state unique to each seat, plus a reference to the flyweight.
public readonly record struct Seat(int Row, int Number, SeatType Type)
{
public string Describe() => $"Row {Row}, seat {Number}: {Type.Category}, {Type.Price} PLN";
}
// Flyweight factory: returns an existing instance instead of creating duplicates.
public sealed class SeatTypeFactory
{
private readonly Dictionary<string, SeatType> _types = new();
public int Count => _types.Count;
public SeatType Get(string category)
{
if (!_types.TryGetValue(category, out var type))
{
type = category == "VIP"
? new SeatType("VIP", 450m, "#C9A227", LoadIcon("vip"))
: new SeatType("Standard", 120m, "#4263EB", LoadIcon("standard"));
_types[category] = type;
}
return type;
}
private static string LoadIcon(string name) => $"<svg><!-- {name}: ~2 KB of path data --></svg>";
}// Flyweight: intrinsic, immutable state shared by thousands of seats.
interface SeatType {
readonly category: string;
readonly price: number;
readonly color: string;
readonly iconSvg: string;
}
// Context: extrinsic state unique to each seat, plus a reference to the flyweight.
class Seat {
constructor(readonly row: number, readonly number: number, readonly type: SeatType) {}
describe(): string {
return `Row ${this.row}, seat ${this.number}: ${this.type.category}, ${this.type.price} PLN`;
}
}
// Flyweight factory: returns an existing instance instead of creating duplicates.
class SeatTypeFactory {
private readonly types = new Map<string, SeatType>();
get size(): number {
return this.types.size;
}
get(category: "VIP" | "Standard"): SeatType {
let type = this.types.get(category);
if (!type) {
type = Object.freeze(
category === "VIP"
? { category, price: 450, color: "#C9A227", iconSvg: loadIcon("vip") }
: { category, price: 120, color: "#4263EB", iconSvg: loadIcon("standard") },
);
this.types.set(category, type);
}
return type;
}
}
const loadIcon = (name: string) => `<svg><!-- ${name}: ~2 KB of path data --></svg>`;
const factory = new SeatTypeFactory();
const seats: Seat[] = [];
for (let row = 1; row <= 200; row++) {
for (let n = 1; n <= 300; n++) seats.push(new Seat(row, n, factory.get(row <= 20 ? "VIP" : "Standard")));
}
console.log(`${seats.length} seats, ${factory.size} shared seat types`);
console.log(seats[0].describe());import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// Flyweight: intrinsic, immutable state shared by thousands of seats.
record SeatType(String category, BigDecimal price, String color, String iconSvg) {}
// Context: extrinsic state unique to each seat, plus a reference to the flyweight.
record Seat(int row, int number, SeatType type) {
String describe() {
return "Row " + row + ", seat " + number + ": " + type.category() + ", " + type.price() + " PLN";
}
}
// Flyweight factory: returns an existing instance instead of creating duplicates.
final class SeatTypeFactory {
private final Map<String, SeatType> types = new HashMap<>();
SeatType get(String category) {
return types.computeIfAbsent(category, c -> c.equals("VIP")
? new SeatType("VIP", new BigDecimal("450"), "#C9A227", loadIcon("vip"))
: new SeatType("Standard", new BigDecimal("120"), "#4263EB", loadIcon("standard")));
}
int count() { return types.size(); }
private static String loadIcon(String name) { return "<svg><!-- " + name + ": ~2 KB of path data --></svg>"; }
}
public class SeatMap {
public static void main(String[] args) {
var factory = new SeatTypeFactory();
List<Seat> seats = new ArrayList<>(60_000);
for (int row = 1; row <= 200; row++)
for (int number = 1; number <= 300; number++)
seats.add(new Seat(row, number, factory.get(row <= 20 ? "VIP" : "Standard")));
System.out.println(seats.size() + " seats, " + factory.count() + " shared seat types");
System.out.println(seats.get(0).describe());
}
}package main
import "fmt"
// SeatType is the flyweight: intrinsic, immutable state shared by thousands of seats.
type SeatType struct {
Category string
Price int
Color string
IconSVG string
}
// Seat is the context: small extrinsic state plus a pointer to the shared flyweight.
type Seat struct {
Row, Number int32
Type *SeatType
}
// SeatTypeFactory returns an existing instance instead of creating duplicates.
type SeatTypeFactory struct{ types map[string]*SeatType }
func NewSeatTypeFactory() *SeatTypeFactory {
return &SeatTypeFactory{types: make(map[string]*SeatType)}
}
func (f *SeatTypeFactory) Get(category string) *SeatType {
if t, ok := f.types[category]; ok {
return t
}
t := &SeatType{Category: "Standard", Price: 120, Color: "#4263EB", IconSVG: loadIcon("standard")}
if category == "VIP" {
t = &SeatType{Category: "VIP", Price: 450, Color: "#C9A227", IconSVG: loadIcon("vip")}
}
f.types[category] = t
return t
}
func loadIcon(name string) string { return "<svg><!-- " + name + ": ~2 KB of path data --></svg>" }
func main() {
factory := NewSeatTypeFactory()
seats := make([]Seat, 0, 60_000)
for row := int32(1); row <= 200; row++ {
for n := int32(1); n <= 300; n++ {
category := "Standard"
if row <= 20 {
category = "VIP"
}
seats = append(seats, Seat{Row: row, Number: n, Type: factory.Get(category)})
}
}
fmt.Println(len(seats), "seats,", len(factory.types), "shared seat types")
s := seats[0]
fmt.Printf("Row %d, seat %d: %s, %d PLN\n", s.Row, s.Number, s.Type.Category, s.Type.Price)
}from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class SeatType:
"""Flyweight: intrinsic, immutable state shared by thousands of seats."""
category: str
price: int
color: str
icon_svg: str
@dataclass(frozen=True, slots=True)
class Seat:
"""Context: extrinsic state unique to each seat, plus a reference to the flyweight."""
row: int
number: int
type: SeatType
def describe(self) -> str:
return f"Row {self.row}, seat {self.number}: {self.type.category}, {self.type.price} PLN"
class SeatTypeFactory:
"""Returns an existing instance instead of creating duplicates."""
def __init__(self) -> None:
self._types: dict[str, SeatType] = {}
def get(self, category: str) -> SeatType:
if category not in self._types:
if category == "VIP":
self._types[category] = SeatType("VIP", 450, "#C9A227", load_icon("vip"))
else:
self._types[category] = SeatType("Standard", 120, "#4263EB", load_icon("standard"))
return self._types[category]
def __len__(self) -> int:
return len(self._types)
def load_icon(name: str) -> str:
return f"<svg><!-- {name}: ~2 KB of path data --></svg>"
if __name__ == "__main__":
factory = SeatTypeFactory()
seats = [
Seat(row, number, factory.get("VIP" if row <= 20 else "Standard"))
for row in range(1, 201)
for number in range(1, 301)
]
print(f"{len(seats)} seats, {len(factory)} shared seat types")
print(seats[0].describe())The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Step by step
- When to use it and when not to
- Related patterns
- In practice
- Quick check
- Summary