What if you could draw thousands of trees without your app crashing or slowing down?
Why Flyweight pattern in LLD? - Purpose & Use Cases
Imagine you are building a drawing app that needs to display thousands of similar shapes, like trees in a forest. If you create a new object for each tree, your app will use a lot of memory and slow down.
Creating separate objects for every similar item wastes memory and processing power. It becomes hard to manage and slows the system, especially when many objects share the same data.
The Flyweight pattern lets you share common parts of objects to save memory. Instead of making a full object for each item, you reuse shared data and only store unique details separately.
class Tree { constructor(type, color, x, y) { this.type = type; this.color = color; this.x = x; this.y = y; } } // Create 1000 trees, each with full data
class TreeType { constructor(type, color) { this.type = type; this.color = color; } } class Tree { constructor(treeType, x, y) { this.treeType = treeType; this.x = x; this.y = y; } } // Share TreeType objects among many trees
It enables building large systems with many similar objects efficiently, saving memory and improving performance.
Video games use the Flyweight pattern to render many identical characters or objects without slowing down the game.
Manual object creation wastes memory when many objects share data.
Flyweight shares common data to reduce memory use.
This pattern improves performance in systems with many similar objects.