Flyweight
- Intent
- When a huge number of objects repeat the same data, split out what they have in common, share it in a few immutable objects, and keep outside what changes in each one.
- Application
- Thousands of logged sets, and nearly all of them repeat the same movements. Share a single object per movement and let each set keep only what's its own.
Three sets, each with its own copy of the movement, highlighted in red: two copies of the squat and one of the deadlift.
The two shared movements appear, the squat and the deadlift, highlighted.
Ana's and Leo's sets point to the same squat, highlighted, and pass it their reps and kilos with line().
MovementCatalog, highlighted, creates the squat and the deadlift just once with computeIfAbsent.
SetLog, highlighted, asks the catalog for get("deadlift") and creates Eva's set with the shared movement.
POST /api/sets travels from the athlete to the controller and to SetLog, which asks the catalog for the deadlift; Eva's set points to the shared movement, highlighted along with SetLog.
Integer.valueOf(100) and MimeTypeUtils.parseMimeType always get the same cached instance, highlighted.
Final view: the athletes, the controller, SetLog, the three sets pointing to two movements and the catalog, all inside the Spring context.
Step 1 of 9
One copy per set
The box logs every set: who, which movement, how many reps and how many kilos. In a month that's thousands, and nearly all of them are squats, deadlifts or thrusters.
In the first version, each set carries the whole movement: name, category, the standard for how it's done (a long text) and the equipment. It's what happens with a denormalized query or a JSON import: every row brings its own texts. With 3,000 sets there are 3,000 copies of two texts; the CopiedMovementLogTest test counts them.
Step 2 of 9
What's shared
Flyweight splits the data in two. What's the same for every set of a movement (name, category, standard, equipment) goes in Movement: it's the intrinsic state, and the object is shared.
Movement is a record and its equipment list is copied with List.copyOf: it's immutable. It has to be, because thousands of sets use it at once.
Step 3 of 9
What belongs to each set
What changes in each set (the athlete, the reps, the kilos) is the extrinsic state. It doesn't go inside the movement: LoggedSet keeps it and passes it to line() when needed.
Ana and Leo squat and share the same Movement object; each has their own line: "Ana · 5 × back squat @ 100 kg", "Leo · 3 × back squat @ 120 kg".
Step 4 of 9
One per name
MovementCatalog is the flyweight factory. get("Back Squat") normalises the name and uses computeIfAbsent: the first time it reads the data and builds the Movement; after that it returns the same object. It's thread-safe because it's a ConcurrentHashMap.
A movement that doesn't exist answers 404 "unknown movement".
Step 5 of 9
The client asks, it doesn't create
SetLog doesn't do new Movement(...): it asks the catalog for the movement and creates a LoggedSet with the shared part and its own. As long as everyone goes through the catalog, no set ends up with its own copy (the type doesn't enforce it: anyone could new Movement(...)).
Step 7 of 9
Over HTTP
Ana, Leo and Eva log a deadlift with POST /api/sets (it answers 201 with their line). GET /api/sets/stats says there are 3 sets and the catalog has built 1 movement. The scene shows Eva's set.
An unknown movement answers 404; reps out of range, 400; and if the demo log fills up (10,000 sets), 409.
Step 8 of 9
Java and Spring already do it for you
Integer.valueOf(100) always returns the same object: the JDK caches the integers from -128 to 127, the most used ones. With 1000, by default, it creates a new one (not guaranteed: the cache can be widened). That's why comparing Integer with == is a bad idea.
Spring does the same with MIME types: MimeTypeUtils.parseMimeType("application/json") keeps recently parsed types in a small LRU cache (multipart ones excluded) and returns the same instance. A web app asks for it thousands of times.
Step 9 of 9
Recap
You started with a copy of the movement in every set and ended up with:
- A flyweight,
Movement, immutable, with what every set shares. - A factory,
MovementCatalog, that creates each one once and hands it out. - Extrinsic state in each
LoggedSet: athlete, reps and kilos.
Its neighbours: a Singleton is one instance of a class; with Flyweight there's one per key (one per movement). In a Composite, repeated leaves can be flyweights, and State and Strategy objects often are. Prototype does the opposite: it copies an object so each one has its own. And String.intern() or the JVM's string deduplication are close relatives: they share equal values, but without splitting state.
When not to use it: with few objects, or little repeated state, the saving isn't worth it. And if the shared data has to change per set, it isn't intrinsic: the flyweight doesn't fit. Measure before you optimise.
Code
CopiedMovementLog.java
public void log(String athlete, String movement, int reps, int kg) {
String[] row = ROWS.get(movement);
// every set gets strings with their own characters, like a denormalized query or a JSON import
sets.add(new CopiedSet(athlete, reps, kg, own(movement), own(row[0]),
own(row[1]), List.of(own("barbell"))));
}Movement.java
/** The flyweight: what every set of a movement has in common. Immutable, so it's safe to share. */
public record Movement(String name, String category, String standard, List<String> equipment) {
public Movement {
equipment = List.copyOf(equipment);
}
/** The extrinsic state (who, how many, how heavy) comes in from outside; it's never stored here. */
public String line(String athlete, int reps, int kg) {
String base = athlete + " · " + reps + " × " + name;
return kg == 0 ? base : base + " @ " + kg + " kg";
}
}MovementCatalogTest.java
SetLog log = new SetLog(new MovementCatalog());
LoggedSet ana = log.log("Ana", "back squat", 5, 100);
LoggedSet leo = log.log("Leo", "back squat", 3, 120);
assertThat(ana.movement()).isSameAs(leo.movement()); // shared: the intrinsic state
assertThat(ana.line()).isEqualTo("Ana · 5 × back squat @ 100 kg");
assertThat(leo.line()).isEqualTo("Leo · 3 × back squat @ 120 kg"); // own: athlete, reps, kgMovementCatalog.java
public Movement get(String name) {
if (name == null || name.isBlank()) throw new InvalidSetException("movement is required");
String key = name.strip().toLowerCase(Locale.ROOT);
return pool.computeIfAbsent(key, this::load); // the same instance, every time
}
private Movement load(String key) {
MovementDefinitions.Row row = MovementDefinitions.ROWS.get(key);
if (row == null) throw new UnknownMovementException(abbreviate(key));
created.incrementAndGet();
return new Movement(key, row.category(), row.standard(), row.equipment()); // built once per name
}SetLog.java
public synchronized LoggedSet log(String athlete, String movement, int reps, int kg) {
if (sets.size() >= capacity) throw new LogFullException(); // a demo, not a database
String who = validate(athlete, reps, kg);
LoggedSet set = new LoggedSet(who, catalog.get(movement), reps, kg); // shared + own
sets.add(set);
return set;
}MovementCatalogTest.java
MovementCatalog catalog = new MovementCatalog();
SetLog log = new SetLog(catalog);
for (int i = 0; i < 3_000; i++) {
log.log("athlete-" + i, i % 2 == 0 ? "back squat" : "deadlift", 5, 100);
}
assertThat(log.size()).isEqualTo(3_000);
assertThat(catalog.created()).isEqualTo(2); // two Movement objects for 3,000 setsSetApiTest.java
for (String who : new String[] {"Ana", "Leo", "Eva"}) {
mvc.perform(post("/api/sets").contentType(MediaType.APPLICATION_JSON)
.content("{\"athlete\":\"" + who + "\",\"movement\":\"deadlift\",\"reps\":5,\"kg\":100}"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.line").value(who + " · 5 × deadlift @ 100 kg"));
}
mvc.perform(get("/api/sets/stats"))
.andExpect(jsonPath("$.sets").value(3))
.andExpect(jsonPath("$.movementsCreated").value(1));SpringDoesItTooTest.java
Integer a = Integer.valueOf(100), b = Integer.valueOf(100);
assertThat(a).isSameAs(b); // -128..127 come from a cache
MimeType json1 = MimeTypeUtils.parseMimeType("application/json");
MimeType json2 = MimeTypeUtils.parseMimeType("application/json");
assertThat(json1).isSameAs(json2); // parsed once, then sharedMovement.java
/** The flyweight: what every set of a movement has in common. Immutable, so it's safe to share. */
public record Movement(String name, String category, String standard, List<String> equipment) {
public Movement {
equipment = List.copyOf(equipment);
}
/** The extrinsic state (who, how many, how heavy) comes in from outside; it's never stored here. */
public String line(String athlete, int reps, int kg) {
String base = athlete + " · " + reps + " × " + name;
return kg == 0 ? base : base + " @ " + kg + " kg";
}
}