design patterns · structural

Flyweight

Uses sharing to support large numbers of fine-grained objects efficiently by separating intrinsic and extrinsic state.

mediumstructural1h
Ask GPTConfidence

Pattern

Overview

Intent

Use sharing to support large numbers of fine-grained objects efficiently.

Real-World Analogy

A chess game - 32 pieces share piece-type objects (color + type = intrinsic state shared); board position is extrinsic state stored per piece.

When you have millions of similar objects (game particles, text glyphs, map tiles), most of their state is shared (intrinsic) and only a small part differs per instance (extrinsic). Flyweight shares the intrinsic state via a factory cache.

Intrinsic state is context-independent and shared (color, sprite). Extrinsic state is context-dependent and passed in (position, velocity). The FlyweightFactory caches and returns shared flyweight instances by key.

When to use

Text editors (shared character glyphs), game development (shared tile/sprite data), caching font or icon objects, large-scale particle systems - anywhere millions of similar objects would be created.

When not to

When the number of objects is small. When objects do not share significant state.

Participants

FlyweightConcreteFlyweightFlyweightFactoryContext

Key Insights

  • Flyweight trades CPU (extrinsic state lookup) for memory (shared intrinsic objects)
  • The factory uses a map keyed by intrinsic state to return cached flyweights
  • Java String pool is a real-world Flyweight implementation
  • Must ensure flyweight objects are truly immutable - shared objects must not be mutated