Skip to main content

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, creating each one only on first request. Every tree stores just a position and a pointer.

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.

Prompt
Write a Go program with the Flyweight pattern: a heavy TreeKind (name, texture) stored once per kind in a map behind a GetKind function that prints when it creates a kind, and light Tree structs holding just a position and a pointer to their kind. Plant four trees of two kinds and print how many trees exist versus how many kinds were stored.
Output: Go program and captured output

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"; the split into shared/unique parts complicates the model.