Notes
The problem
Here is the naive design. Each FatSeat holds its row, number and sold flag, and also its tier name, colour, a two kilobyte icon and a perks line. But there are only four tiers. So sixty thousand seats store sixty thousand copies of just four icons. That is about one hundred and twenty megabytes of duplicates, on a phone, for one screen. Garbage collection slows down and older phones run out of memory.
final class FatSeat {
int row, number;
boolean sold;
String tier; // "Gold"
String colourHex; // "#d4a017"
byte[] icon; // 2 KB image
String perks; // "free water"
}
60,000 seats x 2 KB icon
= about 120 MB of copies The idea
The idea in one sentence: share the part that is the same, and keep the part that differs outside. The shared part is called intrinsic state. It is the same for many objects and never changes: tier, colour, icon and perks. The unique part is called extrinsic state: row, seat number and whether it is sold. The flyweight object holds only intrinsic state. Extrinsic state is stored elsewhere and passed in when needed.
- intrinsic state:
- same for many objects,
- never changes
- tier, colour, icon, perks
- extrinsic state:
- different for each object,
- kept outside, passed in
- row, number, sold
The structure
Four roles. SeatStyle is the flyweight: small, immutable and shared. SeatStyleFactory hands out styles and makes sure there is exactly one object per tier. SeatMap is the context: it keeps the per seat data, row, number and sold flag, plus a reference to the right shared style. BookingScreen is the client that draws the map. Only four SeatStyle objects ever exist, whatever the size of the stadium.
- flyweight: SeatStyle
- immutable, shared
- factory: SeatStyleFactory
- same object per key
- context: SeatMap
- per-seat arrays plus a
- style reference per seat
- client: BookingScreen
Code: the flyweight
In code, SeatStyle has only final fields: tier, colour, icon and perks. Nothing in it can change after creation, which is what makes sharing safe. Notice the tooltip method. It does not store the row, the number or the sold flag. They come in as arguments, every time. That is the core trick of the pattern: the shared object works on extrinsic state it is given, never on state it keeps.
final class SeatStyle {
private final String tier, colourHex;
private final byte[] icon;
private final String perks;
String tooltip(int row, int number,
boolean sold) {
return tier + " row " + row + " seat "
+ number + (sold ? " sold" : "");
}
} Code: the factory
The factory keeps a map from tier name to style. Ask for Gold the first time and it loads the icon and builds the object. Ask again and you get the very same object back. Using a ConcurrentHashMap with compute if absent means two threads asking for Gold at the same moment still end up sharing one instance. Callers must never call new SeatStyle themselves, or sharing quietly breaks.
final class SeatStyleFactory {
private final Map<String, SeatStyle>
cache = new ConcurrentHashMap<>();
SeatStyle styleFor(String tier) {
return cache.computeIfAbsent(
tier, this::load);
}
} Code: the context
The SeatMap context stores the extrinsic state compactly, in plain arrays: a short for the row, a short for the seat number, a boolean for sold, and one reference to the shared style. To describe seat i, it reads that seat's values and passes them into the style. There is no Seat object here at all. A flyweight design often removes the per item object completely.
final class SeatMap {
private final short[] rows, nums;
private final boolean[] sold;
private final SeatStyle[] style;
String tooltip(int i) {
return style[i].tooltip(rows[i],
nums[i], sold[i]);
}
} Run-through
Follow one redraw. The booking screen asks the seat map for rows twenty eight to thirty two. For each seat, the map reads that seat's row, number and sold flag from its arrays, takes the style reference it got from the factory when the map was built, and passes the values in. Every Gold seat on screen is described by the same Gold object. Thousands of calls, four objects doing all the work.
The memory maths
Now the maths. Naive: sixty thousand seats times a two kilobyte icon is about one hundred and twenty megabytes. Flyweight: four styles at two kilobytes each is eight kilobytes, plus about nine bytes per seat for two shorts, a boolean and a reference. That is about half a megabyte in total, more than two hundred times smaller. Do this sum out loud in an interview. The pattern only pays off when the shared part is big and the count is high.
- naive:
- 60,000 x 2 KB icon
- = about 120 MB
- flyweight:
- 4 styles x 2 KB = 8 KB
- + 60,000 x ~9 bytes
- (2 shorts, 1 boolean,
- 1 reference)
- = about 0.55 MB
Already in Java
Java uses this idea itself. Integer value of always returns a shared, cached object for values from minus one hundred and twenty eight to one hundred and twenty seven, and autoboxing calls value of. So two boxed one hundred twenty sevens are the same object, while two boxed one thousands are usually different objects. Boolean value of returns one of two shared constants, and string literals are shared through the string pool. This is also why boxed numbers are compared with equals.
Integer a = Integer.valueOf(127); Integer b = Integer.valueOf(127); a == b // true: same cached object Integer c = Integer.valueOf(1000); Integer d = Integer.valueOf(1000); c == d // false on a default JVM // so compare boxed numbers // with equals(), never ==
Immutability is a must
Because one object is shared by thousands of users, it must be immutable. Make every field final, add no setters, copy arrays when they come in and never hand them out, and create objects only through the factory. If someone could change the Gold colour on one seat, it would change on every Gold seat, and on every thread. Immutable flyweights need no locks at all.
- • every field final
- • no setters
- • copy arrays in, never
- hand them out
- • create only via the factory
- then any number of threads
- can share it with no locks
When to use it
Use Flyweight when you have a huge number of objects, most of their state repeats, the repeated part is heavy, and memory is a real, measured problem. Do not use it for a few hundred objects or when little state is shared. The pattern has a cost: state is split across classes, there is a factory to go through, and the code is harder to read. Measure with a heap dump or a profiler first.
- worth it when:
- • a huge number of objects
- • most of their state repeats
- • the repeated part is heavy
- • memory is a measured problem
- not worth it when:
- • a few hundred objects
- • little state is shared
- • the split state hurts
- readability more than it saves
Flyweight vs others
How does it differ from its neighbours? A singleton has exactly one instance. A flyweight factory has one shared instance per key, here one per tier. An object pool, like a database connection pool, lends a mutable object to one user at a time and takes it back. A flyweight is immutable and used by many at the same time. And a plain cache stores results, while a flyweight factory is a cache whose values are shared building blocks.
- Singleton:
- exactly one instance
- Flyweight:
- one shared instance PER KEY
- Object pool:
- lends a mutable object to
- one user at a time
- Flyweight:
- immutable, used by many
- at the same time
In LLD interviews
In interviews, Flyweight comes up when the question pushes on scale. A movie or stadium booking system shares seat types instead of copying them per seat. A game shares one model and texture across thousands of bullets or tiles. A text editor keeps one object per font style, not per character. A chess server can use twelve shared piece objects for every game it hosts. The common mistake is giving the shared object a setter.
- • movie or stadium booking:
- shared seat types
- • games: bullets and tiles
- share a model and texture
- • text editor: one object per
- font style, not per letter
- • chess server: 12 shared
- piece objects for all games
- mistake: a mutable flyweight
Say it like this
How to say it. Each seat gets a shared SeatStyle per tier from a factory. Row, number and sold flag live in compact arrays inside SeatMap and are passed into the style when needed. Styles are immutable, so every thread can share them without locks. That takes the map from about one hundred and twenty megabytes to under one megabyte. Short, concrete, and it shows you did the maths.
- "Seats share one SeatStyle
- per tier from a factory.
- Row, number and sold flag
- live in arrays in SeatMap
- and are passed in. Styles
- are immutable, so threads
- share them freely. Memory
- drops from ~120 MB to
- under 1 MB."