Skip to content

Design Patterns

Flyweight

Reusing a shared instance takes O(1) time to look up (a constant amount). The memory you save grows with however many objects would otherwise have duplicated the same data.

The idea, in plain English

Flyweight means sharing one copy of a reused thing, instead of making a fresh copy every time. Picture a forest with ten thousand trees. Every 'Oak' tree looks identical — same shape, same texture. So instead of storing that heavy picture ten thousand times, all the oak trees point to the ONE shared 'Oak' picture. Each tree only remembers its own tiny bit of unique info, like where it's planted.

How it works

  1. 1You split an object's data into 'shared' parts (the same for many copies of the object) and 'unique' parts (different for each one).
  2. 2You keep a factory that hands out the shared part. The first time a certain kind is asked for, it gets created and stored. Every time after, you get back that same stored copy.
  3. 3Each individual object only keeps its own unique data, and borrows the shared part when it needs it. Nothing heavy gets duplicated.

When you'd use it

Use this when you need huge numbers of similar objects, and storing full data in every single one would waste a lot of memory. Examples: trees in a game world, characters in a text editor, or icons in a big list.

Common beginner mistakes

  • Don't store unique, per-object data (like position) inside the shared object. That breaks the sharing, since every user would overwrite it.
  • Don't share objects that aren't actually safe to share, because something might quietly depend on each copy staying separate.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Oak(Green) at (1,2)
Oak(Green) at (5,6)
Pine(DarkGreen) at (9,1)
Same oak type object? yes
Shared types stored: 2

Not sure this is the right topic? See the learning paths → or where this leads →