Card 02/ 08

ConceptDifficulty: Intermediate1 min

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.

Flyweight participants
Each participant and its role
ParticipantRole
FlyweightHolds the intrinsic state, never changes it, and takes the extrinsic state as an argument to operation.
FlyweightFactoryKeeps a pool of flyweights by key, and returns the stored one for a key it has seen, creating it only the first time.
ClientAsks 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.

Where each kind of state is stored
StateExampleWhere it lives
IntrinsicA species' mesh and textureInside the flyweight, once per key
ExtrinsicA tree's positionWith 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.