Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 57 ยท Structural Patterns

Flyweight

Learn the Flyweight design pattern: split intrinsic from extrinsic state and share objects to save memory, with a text editor glyph example and size estimates.

The Flyweight pattern saves memory by sharing the parts of objects that are identical instead of storing a private copy in each one. When a program needs hundreds of thousands of small, similar objects, most of their data is usually the same. Flyweight pulls that repeated data into a few shared objects and leaves only the truly unique values in each user of them.

The textbook case is a text editor. A document with 100,000 characters could create 100,000 Character objects, each holding a letter, a font name, a size and a color. But the document only uses a few dozen distinct combinations of those four things. If the shared combination is stored once, each character in the document needs only its position and a reference to the shared glyph.

Two kinds of state

Intrinsic Same for many objects, such as the letter and font. Shared.
Extrinsic Different per use, such as the position. Passed in.

Only intrinsic state lives inside the flyweight.

1 / 2

Intrinsic and extrinsic state

The whole pattern depends on sorting an object's data into two buckets:

  • Intrinsic state is context-independent and can be shared: the character "a", the font "Serif", the size 12. It lives inside the flyweight and must never change after creation.
  • Extrinsic state depends on where and how the object is used: the row and column of this particular "a". It is stored outside the flyweight (in a context object or an array) and passed to the flyweight's methods when needed.

Because many clients share one flyweight, it must be immutable. If one client could change the font of the shared "a", every other "a" in the document would change too.

classDiagram
    class GlyphFactory {
        -cache
        +get(char, font, size)
    }
    class Glyph {
        +char
        +font
        +size
        +draw(row, col)
    }
    class PlacedGlyph {
        +row
        +col
    }
    GlyphFactory --> Glyph : creates and caches
    PlacedGlyph --> Glyph : shares

Many placed glyphs (position only) point at a small set of shared glyphs (appearance).

Glyphs in a text editor

The factory returns the same object for the same combination. A PlacedGlyph holds only the extrinsic data. The program checks how many distinct Glyph objects exist compared with the number of placed characters.

JS Sharing glyphs across a document

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The 18 characters of the sentence need only 7 distinct glyphs (t, o, space, b, e, r and n); every repeated letter reuses an existing one. In a real document the ratio is far more dramatic: a book has a few hundred thousand characters but only a few hundred distinct glyph styles.

Measuring the savings

Real memory use depends on the engine, so a browser console editor can't report bytes exactly. This example estimates it with a simple model: a private object costs 40 bytes (letter, font reference, size, color and header), a position record costs 16 bytes, and a shared reference costs 8 bytes. The numbers are assumptions chosen to show the shape of the saving, not measurements of any specific runtime.

JS Estimating the memory saved

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The saving grows with the number of objects and converges to the fraction of each object that was shared. In this model it is about 57 percent, because the 24 bytes of per-character data (position plus reference) remain. If the shared part is larger relative to the extrinsic part, the saving is bigger. If every object is different, nothing can be shared and the pattern gains nothing.

Where flyweights appear

  • Games and graphics. A forest of 50,000 trees shares a handful of mesh and texture objects; each tree stores its position, scale and rotation.
  • Strings. Java interns string literals and Integer.valueOf caches small values (-128 to 127), so equal values often share one object. Python interns small integers and some strings in the same spirit.
  • Fonts, icons and map tiles. A UI reuses one icon bitmap in hundreds of places.
  • Enum-like constants and value objects. Immutable values such as colors or currencies can be created once and reused.

When Flyweight is the wrong tool

  • You have not measured a problem. The pattern adds a factory, a cache and a split between two kinds of state. Do it only when memory profiling shows many near-identical objects.
  • Few repeats. If objects are mostly unique, there is nothing to share.
  • Mutable state. A shared object that anyone can change is a source of bugs. If you cannot make the shared part immutable, do not share it.
  • Extrinsic state is expensive to compute or pass. Saving memory by recalculating values on every call trades memory for CPU time. Measure both.
  • Cache growth. A factory that never forgets a key can itself leak memory if the number of distinct combinations is unbounded. Use a bounded cache or weak references when needed.

Flyweight is often combined with Composite (leaf nodes shared as flyweights) and with Factory Method (the cache-checking factory). It is related to Singleton only in that both restrict instance creation: a singleton has one instance of one class; flyweights have one instance per distinct intrinsic state.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the Flyweight pattern, which data is stored inside the shared object?

    Intrinsic state is the part that can be shared. Extrinsic state is kept outside and passed in when needed.
  2. 2. Why must flyweight objects be immutable?

    Sharing means one change becomes visible everywhere. Freezing or otherwise protecting the object prevents accidental cross-client effects.
  3. 3. A document has 1,000,000 characters but only 200 distinct font-and-letter combinations. How many glyph objects does a flyweight factory create?

    The factory creates one glyph per distinct combination and reuses it, so 200 shared objects serve all the characters.
  4. 4. When is Flyweight likely NOT worth using?

    Flyweight adds complexity. Without many duplicates there is nothing to share, and without a measured problem the added code is not justified.
  5. 5. What is the role of the factory in Flyweight?

    The factory guarantees that equal intrinsic state maps to one shared instance, usually by keeping a map from a key to the created object.

Summary

  • Flyweight saves memory by sharing the identical (intrinsic) part of many objects and passing the varying (extrinsic) part in.
  • A factory with a cache hands out shared instances; shared objects must be immutable.
  • The saving grows with the number of objects and is limited by the share of data that cannot be shared.
  • Games, UI icons, fonts and interned strings use the idea.
  • Use it only for a measured memory problem with many near-identical objects; watch unbounded caches.

Next lesson: Proxy.