Cheatsheet

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.

Structure (UML)

Spring contextAna · 5 × squatAthletesMovement: back squatLeo · 3 × squatSetControllerMovementCatalogSetLogMovement: deadliftEva · 5 × deadlift

Participants

  • Flyweight (Movement), the shared (intrinsic) state; immutable
  • FlyweightFactory (MovementCatalog), creates each flyweight once and always hands back the same one
  • Client (SetLog, LoggedSet), keeps its own (extrinsic) state and passes it in when needed

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";
    }
}

Pros

  • One object per movement, even with thousands of sets
  • Common data lives in one place, with no copies to maintain
  • Movements can be compared by identity

Cons

  • It only pays off with many objects and lots of repeated state; otherwise it's complication for nothing
  • The flyweight must be immutable, or a change would show up in every set at once
  • The extrinsic state is passed on every call, and the code gets a bit more indirect

← Flyweight · Run it