Flyweight Pattern
The Flyweight pattern: sharing the common part of many small objects so that a program holding millions of them still fits in memory.
A game draws a million trees, a text editor holds every character of a long document, and a particle system animates ten thousand sparks. Most of what each object stores is identical to thousands of others: the same species, the same font, the same sprite. The Flyweight pattern stores that common part once and shares it, while each object keeps only what is its own, or has it passed in on every call.
This topic opens on that problem and the split it rests on, intrinsic state that is shared and extrinsic state that varies, then reads the participants off the class diagram, where a factory hands out the shared objects. The template counts how many objects a factory really made in Python, Java and TypeScript.
Two examples follow: the characters of a text editor, where 46,000 characters share ten glyph objects, and Java's Integer.valueOf, which returns a cached object for small numbers. The gotcha is what that cache does to == on boxed integers, and the exercise sorts a particle's state into shared and per-particle.
By the end you can recognise a flyweight, decide which state it may hold, and predict when Java's Integer cache applies.
Contents
8 cardsnot started