Card 08/ 08

RecapDifficulty: Advanced1 min

Recap: Flyweight Pattern

Share what is the same, pass in what differs, and never rely on identity.

Flyweight stores the repeated part of many small objects once, and shares it.

  • Intent. Use sharing to support large numbers of fine-grained objects efficiently.
  • Two kinds of state. Intrinsic state is shared and lives in the flyweight; extrinsic state varies and is held or passed in by the client.
  • Participants. The flyweight, which is immutable, the factory that pools flyweights by key, and the client.
  • In the wild. Java's Integer.valueOf, which caches -128 to 127 by default and serves autoboxing.
  • The trap. == on boxed integers is true inside the cache and false outside it; compare with equals.
  • When not. A few hundred objects, state that must change per object, or code that relies on identity.