0
0
LLDsystem_design~3 mins

Why Flyweight pattern in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could draw thousands of trees without your app crashing or slowing down?

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
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
After
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
What It Enables

It enables building large systems with many similar objects efficiently, saving memory and improving performance.

Real Life Example

Video games use the Flyweight pattern to render many identical characters or objects without slowing down the game.

Key Takeaways

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.