Flyweight Pattern

Share the data that many small objects have in common, so a million objects cost little more than a handful.

Overview

The Flyweight pattern is one of the structural patterns in the Gang of Four book, Design Patterns (Gamma, Helm, Johnson and Vlissides, 1994). It answers one question: what do you do when a program needs a huge number of small objects, and most of them carry the same data? Instead of storing that data inside every object, you store it once in a shared object, the flyweight, and let every user point at it.

Interviewers use Flyweight to test whether you can tell shared state from per-object state, and whether you know the cost of sharing: the shared part must never change. A strong answer names the two kinds of state, shows the factory that hands out shared objects, and says where the pattern already lives in the platform you use.

The problem it solves

A text editor with a million characters, a game with a forest of ten thousand trees, a map with a million markers: each item is tiny, but the items add up. If each one stores its own copy of a font, a texture or an icon, memory is spent a million times on data that has only a few distinct values.

Without Flyweight, every object stores all of its data, so one million objects means one million copies of the font data. Changing a shared value then means touching every object. With Flyweight, each object stores only what makes it different, and the few distinct fonts exist once each. Changing a shared value means replacing one flyweight. The price is design work: plain objects are simple to write, while Flyweight needs a factory and a clear split of state.

Interview questions

  • What is the difference between intrinsic and extrinsic state, and how do you decide which is which?
  • How does the flyweight factory work, and why must clients go through it?
  • Why must a flyweight be immutable? Show the bug.
  • Where does Flyweight appear in Java and Python, and why does it make == unreliable?
  • When does Flyweight make a design worse?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio