Flyweight is for programs that need a huge number of similar objects: the trees of a game forest, the characters of a document, the markers on a map. It splits each object's state in two. The part that is the same for many objects (intrinsic state, such as a tree species' texture) moves into a small number of shared, immutable flyweight objects; the part that differs (extrinsic state, such as each tree's position) stays outside and is passed in when the flyweight does its work. A factory hands out the shared objects by key, so a million trees of two species need two copies of the heavy data instead of a million.
Think of it like
Rubber stamps in a post office
A post office does not engrave a new "PRIORITY" stamp for every parcel. It keeps one stamp per word on a rack, and the clerk inks the right one and presses it wherever the parcel needs it. The stamp holds what never changes (the letters and the border); the clerk supplies what does (which parcel, where on it, which ink). Ten thousand parcels a day, a dozen stamps. Nobody would carve a date into a shared stamp, because every parcel would then carry the same date: anything that differs per parcel has to come from the hand that holds the stamp.
The problem
A game draws a forest. Each tree has a position and a species, and a species brings heavy data with it: its name, and above all a texture, which in a real game is megabytes of bark and leaf pixels (or a mesh plus textures). The first version builds that species data again for every tree. This is the Before version in the visualizer above.
class TreeType {
static created = 0;
private readonly texture: string;
constructor(private readonly name: string) {
this.texture = name + ".png"; // megabytes of pixels
TreeType.created++;
}
draw(x: number, y: number) {
return `${this.name} at ${x},${y}`;
}
}
class Tree {
constructor(
private x: number,
private y: number,
private type: TreeType,
) {}
draw() {
return this.type.draw(this.x, this.y);
}
}
const t1 = new Tree(2, 5, new TreeType("oak"));
const t2 = new Tree(8, 1, new TreeType("fir"));
const t3 = new Tree(4, 7, new TreeType("oak")); // oak data again
const t4 = new Tree(6, 3, new TreeType("fir")); // fir data againRun Before and watch the objects view: next to each tree sits its own TreeType, named oak, fir, oak2 and fir2, and the static counter TreeType.created in the TreeType «class» box ends at 4. Two of those four objects are exact copies: oak2 holds the same name and texture as oak. Four trees make the waste look small. A real forest does not have four trees.
Trees in the level
1,000,000
2 species
Textures, one per tree
about 1 TB
if each texture is 1 MB
Textures, one per species
2 MB
plus small per-tree objects
- Memory grows with the number of objects, not with the variety. A million trees of two species hold a million textures, although only two are different. Long before you run out of memory, the duplicates crowd the CPU caches and keep the garbage collector busy.
- Creating objects gets slow. Each new tree pays for loading or decoding the heavy data again, even though the result is identical to one already in memory.
- Nothing tells the copies apart.
oakandoak2are equal in every field, so there is no reason for both to exist. The design simply never asked which state is per tree and which is per species. - The smell to look for. Many objects (thousands or more) whose fields are mostly the same values repeated, with only a few fields that really differ per object. Count the distinct combinations of the repeated fields: if there are far fewer combinations than objects, those fields can be shared.
The pattern
Intent: use sharing to support large numbers of fine-grained objects efficiently (Gang of Four). The key is to split an object's state into two kinds and treat them differently.
| Intrinsic state | Extrinsic state | |
|---|---|---|
| What it is | What is the same for every object of a kind | What differs from object to object, or depends on context |
| In the forest | Species name, texture, mesh | Position (x, y), health, rotation |
| In a text editor | A character's glyph shape for one font and size | Where it is on the page, its color, which paragraph it is in |
| Where it lives | Inside the shared flyweight | In the client or a small context object (Tree) |
| How it reaches the work | Read from the flyweight's own fields | Passed in as arguments: type.draw(x, y) |
| May it change? | No: the flyweight is immutable once created | Yes, freely, because nobody else sees it |
- Flyweight (
TreeType) - Holds only intrinsic state and never changes after construction. Its methods take the extrinsic state as parameters (
draw(x, y)). One instance serves every object of its kind. - Flyweight factory (
TreeFactory) - The only place flyweights are created.
get(key)returns the cached flyweight for that key or creates, caches and returns a new one. The key is made of the intrinsic values; here the species name determines them all. - Context (
Tree) - The light per-object part: the extrinsic state plus a reference to its flyweight. The Gang of Four simply say the client computes or stores the extrinsic state; a small context object per item is the most common way to store it, but arrays of positions work too.
- Client
- Asks the factory for flyweights instead of constructing them, and supplies the extrinsic state when it uses them.
What the visualizer shows
- Class diagram:
Treeholds a reference toTreeType(thetypefield) andTreeFactoryaggregates manyTreeTypes in itscache. What a class diagram cannot show is the multiplicity at runtime: many trees point at one type. That is the objects view's job. - Objects at runtime: in With Flyweight, the factory sits on top with its
cachepointing at the two shared types,oakandfir, which flank the client. The four trees around them each point at one of those two. Two trees point atoakand two atfir; in Before each type has exactly one tree pointing at it. - The memory figure: the
TreeType «class»box at the bottom (top row in Before) holds the static countercreated. It ends at 2 with Flyweight and at 4 in Before. The toolbar'sobjectsstat counts every object including the trees and the factory, so readcreatedfor the heavy ones. - The cache at work: the first
factory.get("oak")createsoakand the cache becomesMap{oak: oak}; the secondget("oak")returns straight away with no create step, and the sequence view shows no new lifeline. - Extrinsic state passed in:
t1.draw()becomesoak.draw(2, 5)andt3.draw()becomesoak.draw(4, 7). The sameoaklifeline answers"oak at 2,5"and then"oak at 4,7", and its fields never change.
Press Play, or step with the arrow buttons; the visualizer runs the classes in the code panel for real, and the caption under the stage explains each step. The Before / With Flyweight toggle switches versions. Add tree health applies the change request to whichever version is shown; touched classes get a badge, and the Change request panel beside the code compares the two versions.
Walkthrough
- 1
One factory, empty cache
With With Flyweight selected, the client creates
factory. Itscacheis an emptyMap, andTreeType.createdis 0. - 2
First oak: a cache miss
factory.get("oak")finds nothing under"oak", so it createsoak(name = "oak",texture = "oak.png", andTreeType.createdbecomes 1), stores it in the cache and returns it. The client createst1withx = 2,y = 5andtype = oak. - 3
First fir: another miss
get("fir")does the same forfir.createdis 2 and the cache isMap{oak: oak, fir: fir}.t2stands at 8,1 and points atfir. - 4
Second oak: a hit
get("oak")findsoakin the cache and returns it: no create step, no second texture.t3(at 4,7) points at the very objectt1points at. - 5
Second fir: a hit
The same for
t4andfir. Four trees exist andTreeType.createdis still 2. The narration states the scale: with a million trees of two species it would still be 2. - 6
Draw passes the position in
t1.draw()callsoak.draw(2, 5), which returns"oak at 2,5". Thent3.draw()calls the sameoakwith(4, 7)and gets"oak at 4,7". The shared object never stored a position; it received one per call. - 7
Add tree health (change request)
With Add tree health applied, every
Treestarts withhealth = 100and the client callst1.damage(30). Onlyt1.healthbecomes 70;t3, the other oak, keeps 100 because health lives inTree, not in the sharedoak.
Before and after
A TreeType per tree
- Each tree is created with
new TreeType(...)of its own - 4 trees make 4 heavy objects;
TreeType.createdends at 4 oakandoak2are identical copies that nobody can tell apart- Memory grows with the number of trees
- Per-tree data could go anywhere, even into the type (it is private anyway)
With Flyweight
- Trees get their type from
factory.get(name) - 4 trees share 2 heavy objects;
TreeType.createdends at 2 - One
oakobject serves every oak, at any position - Memory grows with the number of species; each tree adds a few small fields
- Per-tree data must stay in
Tree: the type is shared and immutable
| Change request: add tree health | Before | With Flyweight |
|---|---|---|
| Existing classes edited | 1 (Tree) | 1 (Tree) |
| New classes | 0 | 0 |
| Lines changed in existing classes | 4 | 4 |
TreeType.created stays 4 in Before and 2 with Flyweight.The numbers are the same on both sides, and that is the honest result: Flyweight does not make this change cheaper. What it changes is where the field is allowed to go. In Before, putting health into TreeType would happen to work, because every tree owns a private copy. With Flyweight that same edit is a bug: oak is shared by t1 and t3, so damaging t1 would damage every oak in the forest. The pattern is a discipline: every new field must be classified as intrinsic or extrinsic before it is added.
Variations
The factory and its key
The cache key must contain every intrinsic value that varies. In the visualizer the species name determines the texture, so the name is enough. A text renderer's glyph depends on the character, the font and the size, so its key is all three: ('l', "Inter", 16) and ('l', "Inter", 24) are different flyweights. Leave a value out of the key and two different objects collapse into one; put an extrinsic value into it and nothing is shared at all. Clients must not be able to bypass the factory, or duplicates come back. Keep the flyweight's constructor package-private or private and offer a static factory method (Glyph.of(...)), or make the factory the only exported way to get one. Because each key maps to exactly one object, flyweights from the factory can be compared by identity (a === b), which is faster than comparing fields. That only holds if every instance really came from the factory.
Thread safety
Immutable flyweights need no locking: any number of threads can read one at the same time. The factory is different. Its get-or-create is a check followed by an insert, and two threads can both see a miss and create two flyweights for one key. Make that step atomic: in Java, ConcurrentHashMap.computeIfAbsent runs the creation at most once per key; in Python or C++, hold a lock around the lookup and the insert. Creating flyweights up front, before any thread starts, avoids the question entirely when the set of keys is known (a fixed list of species).
Eviction and weak references
A factory that only ever adds entries keeps every flyweight alive forever. That is fine for a bounded key set (two species, 256 byte values). It is a memory leak when keys are unbounded, such as interning every string a server ever receives. Two common fixes: bound the cache with an eviction policy (an LRU & LFU Cache, where an evicted flyweight is simply rebuilt on the next request), or hold the flyweights through weak references, so an entry disappears once no object uses that flyweight any more. The Java documentation of WeakReference names "canonicalizing mappings" as its most common use, and Guava ships Interners.newWeakInterner().
import weakref
class TreeType:
def __init__(self, name: str) -> None:
self.name = name
class TreeFactory:
def __init__(self) -> None:
# Values are held weakly: the cache alone keeps nothing alive.
self._cache = weakref.WeakValueDictionary()
def get(self, name: str) -> TreeType:
t = self._cache.get(name)
if t is None:
t = TreeType(name)
self._cache[name] = t
return t
f = TreeFactory()
oak = f.get("oak")
print(len(f._cache)) # 1
del oak # the last strong reference is gone
print(len(f._cache)) # 0 in CPython; later in runtimes with a tracing GCUnshared flyweights and storing extrinsic state compactly
The Gang of Four allow flyweight classes that are not shared: in their document editor, a character glyph is shared, but a row or a column of glyphs is not, although all of them implement the same glyph interface. That makes Flyweight combine naturally with Composite: the leaves of a large tree are shared flyweights, and the composites that arrange them are ordinary objects. Shared leaves cannot keep a parent pointer or their own position, so the composite passes position down while it walks. Extrinsic state does not have to live in one small object per item either. A game can keep positions in a flat array of numbers and a parallel array of species indices; a text editor stores fonts as runs ("characters 0 to 120 are Inter 16") instead of one font per character. The fewer objects the extrinsic state needs, the more the pattern saves.
In real code
| Where | What is shared | Notes |
|---|---|---|
Java Integer.valueOf(int) | One Integer per value from -128 to 127 | Required by the Java Language Specification for boxing in that range; the upper bound can be raised with -XX:AutoBoxCacheMax. Short, Byte, Long and Character cache small values too, and Boolean.valueOf returns TRUE or FALSE |
Java String.intern() and string literals | One String per distinct content in the string pool | Literals and constant expressions are interned automatically; intern() returns the pooled instance. .NET has the same idea in String.Intern |
| CPython small integers | One object per int from -5 to 256 | An implementation detail of CPython: is on small ints happens to be true, but code must use == |
| CPython string interning | Identifier-like strings, and anything passed to sys.intern() | Automatic interning of literals is an implementation detail; sys.intern() is the documented way to ask for it, useful for dictionary keys repeated millions of times |
Java Swing BorderFactory | Border objects | Its documentation says it hands out references to shared Border instances wherever possible, so many components can use one border |
| Text rendering | One rasterized glyph per character, font and size | Renderers draw each glyph once into a glyph cache or a GPU texture atlas, then draw every occurrence from it at its own position and color |
| Game engines | One mesh and material for many objects | GPU instancing draws many copies of one mesh in a single call, with only per-instance data (transform, color) supplied for each copy |
The first four rows go by a more common name, interning: keeping exactly one canonical instance per value. Interning is Flyweight applied to value objects, where the whole object is intrinsic state and there is no extrinsic state at all. The last two rows are the pattern's original setting. The Gang of Four built their example on a document editor that shares one glyph object per character, and graphics systems still use the same split: the shape is shared, the placement is per occurrence.
When to use it, and when not to
Reach for Flyweight when
- The program creates a very large number of objects (thousands to millions) and memory is a measured problem
- Most of each object's state repeats across many objects, with few distinct combinations
- The repeated state can be made immutable
- The rest of the state can be passed in or computed when needed
- Object identity does not matter to clients, or sharing it is acceptable
Skip it when
- There are only a few hundred objects: the saving is noise and the indirection is not
- State is mostly unique per object, so there is little to share
- The shared part needs to change per object, now or likely later
- Passing extrinsic state everywhere would complicate every call site
- You have not measured: a profiler should show the duplicated data first
- Cost: CPU for memory. Every call passes the extrinsic state in, and sometimes it has to be computed or looked up first (which font applies at this index?). The savings must be worth that work.
- Cost: indirection. Code reads
tree.type.textureinstead oftree.texture, and the factory lookup costs a hash computation per request. - Cost: rigidity. Once a field is intrinsic, no object can have its own value for it. If designers later want one oak to be autumn colored, that becomes a new key (a new flyweight), not a field change.
Flyweight vs similar patterns
| Pattern | How many instances | Shared how | Key difference from Flyweight |
|---|---|---|---|
| Flyweight | One per distinct intrinsic value (per key) | By everyone at once, read-only | The reference point for this table |
| Singleton | Exactly one for the whole program | By everyone at once | One object, usually with mutable state and a global access point. A flyweight factory is "one instance per key", and the factory itself is often a single instance |
| Object Pool | A bounded set of interchangeable objects | Exclusively: borrowed, used, returned | Pooled objects are mutable and reset on return; flyweights are immutable, never checked out, and used by many at the same moment |
| Prototype | As many as you clone | Not shared: each caller gets a copy | The opposite answer to "many similar objects": copy so each can diverge, versus share because they never will |
| Composite | Any | A tree of parts | Often combined: shared flyweight leaves inside a composite, which then passes position down because a shared leaf cannot store it |
| Factory Method | A new object per call | Not shared | Decides which class to create. A flyweight factory decides whether to create at all, and returns an existing object when it can |
| Caching (Cache-Aside, Read-Through & Write-Behind) | One entry per key | Read by many | A cache stores values to avoid recomputing them and may go stale; a flyweight factory stores objects to avoid duplicating them, and an immutable flyweight is never stale |
Implementation
The visualizer's scenario as a complete program: TreeType is the immutable flyweight with a static counter of how many were created, TreeFactory caches one per species, and Tree is the light context holding position, health (the change request) and a reference. The demo plants 100,000 trees of two species, shows that only two TreeType objects exist, draws two trees and damages one of them.
class TreeType:
"""Flyweight: intrinsic state only, never changed after creation."""
created = 0
__slots__ = ("_name", "_texture")
def __init__(self, name: str) -> None:
self._name = name
# Stands in for loading megabytes of bark and leaf pixels.
self._texture = f"{name}.png"
TreeType.created += 1
def draw(self, x: int, y: int) -> str:
# Extrinsic state (the position) comes in as arguments.
return f"{self._name} at {x},{y}"
class TreeFactory:
"""Flyweight factory: one TreeType per species, made on first use."""
def __init__(self) -> None:
self._cache: dict[str, TreeType] = {}
def get(self, name: str) -> TreeType:
tree_type = self._cache.get(name)
if tree_type is None:
tree_type = TreeType(name)
self._cache[name] = tree_type
return tree_type
class Tree:
"""Context: extrinsic state plus a reference to the shared type."""
# No per-object __dict__: a real saving at 100,000 trees.
__slots__ = ("_x", "_y", "_type", "_health")
def __init__(self, x: int, y: int, tree_type: TreeType) -> None:
self._x = x
self._y = y
self._type = tree_type
self._health = 100 # extrinsic: differs per tree
def damage(self, n: int) -> None:
self._health = max(0, self._health - n)
@property
def health(self) -> int:
return self._health
def draw(self) -> str:
return self._type.draw(self._x, self._y)
factory = TreeFactory()
trees = []
for i in range(100_000):
species = "fir" if i % 3 == 0 else "oak"
trees.append(Tree(i % 500, i // 500, factory.get(species)))
print(len(trees), TreeType.created) # 100000 2
print(trees[0].draw()) # fir at 0,0
print(trees[4].draw()) # oak at 4,0
trees[4].damage(30) # health is per tree, so only trees[4] changes
print(trees[4].health, trees[5].health) # 70 100Key takeaways
- Flyweight splits state in two: intrinsic state, the same for many objects, goes into shared immutable flyweights; extrinsic state, which differs per object, stays outside and is passed in (
type.draw(x, y)). - A factory caches one flyweight per key, and the key must contain every intrinsic value. In the visualizer 4 trees end with
TreeType.createdat 2 instead of 4, and a million trees of two species would still need 2. - Flyweights must be immutable: that is what makes sharing them safe, including across threads. The factory's get-or-create still needs to be atomic under concurrency.
- The "Add tree health" request costs the same 4 lines in both versions, but with Flyweight the field must go in
Tree: putting it in the sharedTreeTypewould damage every oak at once. - Interning (
Integer.valueOf,String.intern, glyph caches) is Flyweight for value objects. Identity sharing is an optimization; compare values with equality, not references. - Use it only for very many objects with mostly repeated state, and measure first: it trades memory for indirection, extra arguments and a stricter design.
Common pitfalls
- Making a flyweight mutable (a setter, a public array field), so one user's change silently affects every object that shares it.
- Storing extrinsic state in the flyweight, such as a position, a parent pointer or per-object health. It either breaks sharing (one key per object) or makes all users see the last value written.
- A cache key that leaves out an intrinsic value, so two different variants (oak at size 16 and size 24) collapse into one flyweight.
- An unbounded factory with unbounded keys, which keeps every flyweight ever requested alive. Bound it, evict, or hold values through weak references.
- Relying on reference equality for values: Java's
Integercache makes==true for 127 and normally false for 128, and CPython's small int cache is an implementation detail.
Interview tips
- Lead with the intrinsic and extrinsic split, and name concrete fields for each. That split is the pattern; the factory is the mechanism.
- Give a memory estimate: objects × duplicated bytes before, against distinct keys × bytes plus objects × context size after. It shows you know when the pattern pays off.
- Mention immutability and thread safety together: shared flyweights need no locks, but the factory's get-or-create must be atomic (
computeIfAbsent). - Be ready to contrast it with Object Pool (exclusive and mutable vs shared and immutable) and Singleton (one instance vs one per key), and to cite
Integer.valueOforString.internas everyday examples.
Real-world applications
- Games and 3D graphics: shared meshes, textures and materials for trees, grass, bullets and particles, often drawn with GPU instancing.
- Text editors and renderers: one glyph per character, font and size, cached and drawn at many positions.
- Maps and charts: shared marker icons and styles for thousands of points.
- Language runtimes: interned strings and cached boxed numbers.
- Compilers and parsers: interned identifiers and symbols, shared type objects for
intorstring. - UI toolkits: shared borders, colors, fonts and icons used by many widgets.
Test yourself
In the visualizer's forest, which state belongs in the shared TreeType?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.