Card 02/ 08
Flyweight Pattern Structure: The Class Diagram
A FlyweightFactory hands out shared Flyweights; the client passes the varying state on each call.
Flyweight has three participants and a client: the flyweight that holds the shared state, the factory that makes sure each flyweight exists once, and the client that keeps or computes the varying state. This card reads their roles off the Gang of Four's class diagram, then sets out where each kind of state lives.
| Participant | Role |
|---|---|
| Flyweight | Holds the intrinsic state, never changes it, and takes the extrinsic state as an argument to operation. |
| FlyweightFactory | Keeps a pool of flyweights by key, and returns the stored one for a key it has seen, creating it only the first time. |
| Client | Asks the factory for flyweights, and keeps or computes the extrinsic state that it passes in. |
The factory is what makes sharing reliable. If clients called the flyweight's constructor themselves, two trees of the same species would get two objects and the saving would be lost. The Gang of Four also allow an unshared concrete flyweight, an object with the same interface that is not pooled, for the rare case that must hold its own state.
| State | Example | Where it lives |
|---|---|---|
| Intrinsic | A species' mesh and texture | Inside the flyweight, once per key |
| Extrinsic | A tree's position | With the client, or passed to operation on each call |
The test for each field is whether two uses of the flyweight could ever need different values for it. If they could, the field is extrinsic, and storing it in the flyweight would force a separate flyweight for every value, which is no sharing at all.
← → move through sections and cards