What It Is
The Flyweight pattern saves memory when a program holds thousands of similar objects: the heavy shared part is stored once and referenced everywhere, while each object keeps only its small unique part.
A forest of 10,000 trees does not need 10,000 textures — it needs 2 tree kinds and 10,000 tiny (x, y, kind) records.
Example: A Forest of Shared Kinds
getKind() hands out shared kind objects from a Map, creating each one only on first request. Every tree stores just a position and a reference.
Many trees, few kinds
Four trees, but creating kind prints only twice — oak and pine exist once each, no matter how large the forest grows. The last two lines read trees planted: 4 and kinds stored: 2.
Output: TypeScript file and captured output
// The heavy shared part — created once per kind.
class TreeKind {
readonly name: string
readonly texture: string
constructor(name: string) {
this.name = name
this.texture = name + ".png"
}
}
const kinds = new Map<string, TreeKind>()
function getKind(name: string): TreeKind {
const found = kinds.get(name)
if (found !== undefined) {
return found
}
console.log("creating kind:", name)
const kind = new TreeKind(name)
kinds.set(name, kind)
return kind
}
// The light per-tree part: a position and a reference.
type Tree = {
x: number
y: number
kind: TreeKind
}
const forest: Tree[] = [
{ x: 1, y: 2, kind: getKind("oak") },
{ x: 3, y: 4, kind: getKind("pine") },
{ x: 5, y: 6, kind: getKind("oak") },
{ x: 7, y: 8, kind: getKind("pine") },
]
console.log("trees planted:", forest.length)
console.log("kinds stored:", kinds.size)
When to Use It
Use it when profiling shows memory pain from many objects that repeat heavy data — map tiles, glyphs, particles, cached styles.
Skip it below thousands of objects, or when the shared part is small. This is an optimization pattern: without the memory problem, it is only complexity.
Pros and Cons
Pros: big memory savings at scale; shared data updated in one place.
Cons: shared objects must be treated as read-only — one careless write changes “every oak in the forest” (marking the shared fields readonly helps); the split into shared/unique parts complicates the model.