Flyweight Pattern — ELI5

Imagine a library with 500 copies of the same book. Instead of printing 500 separate copies, the library could keep one copy and give everyone a card that says “go read the book on shelf 3.” Same result, way less paper.

That’s the Flyweight Pattern. When many objects share the same data, you store that data once and let everyone point to the shared copy instead of each having their own duplicate.

Think about a video game with a forest of 10,000 trees. Every tree has a texture (the image that makes it look like a tree), a 3D model, and color values. If each tree stored its own copy of that texture, you’d run out of memory fast. Instead, all pine trees share one texture, all oak trees share another. Each individual tree only stores its own position — the unique part.

The shared stuff (texture, model) is the flyweight. The unique stuff (position, rotation) stays with each object.

In real life, this pattern shows up everywhere. Fonts on your computer work this way — the letter “e” doesn’t get stored separately for every “e” on your screen. There’s one “e” shape, and the computer just uses it wherever needed.

The pattern is about being smart with memory. When you notice thousands of objects all carrying identical data, that’s your signal to share instead of copy.

The one thing to remember: Flyweight means “share the stuff that’s the same, only store what’s different” — saving memory when you have lots of similar objects.

pythondesign-patternsoop

See Also

  • Python Adapter Pattern How Python's Adapter Pattern works like a travel power plug — making incompatible things work together.
  • Python Bridge Pattern Why separating what something does from how it does it keeps your Python code from becoming a tangled mess.
  • Python Builder Pattern Why building complex Python objects step by step beats cramming everything into one giant constructor.
  • Python Composite Pattern How the Composite Pattern lets you treat a group of things the same way you'd treat a single thing in Python.
  • Python Facade Pattern How the Facade Pattern gives you one simple button instead of a confusing control panel in Python.