0
0
LLDsystem_design~3 mins

Why Composite pattern in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could treat a single file and a whole folder the exact same way in your code?

The Scenario

Imagine you have a folder with files and subfolders, and you want to perform actions like opening or deleting on them. Doing this manually means writing separate code for files and folders, and then more code to handle folders inside folders, which quickly becomes messy.

The Problem

Manually handling each file and folder type separately leads to repetitive code and lots of special cases. It's easy to forget to handle a new folder inside a folder, causing bugs. The code becomes hard to read and maintain as the structure grows.

The Solution

The Composite pattern treats individual objects and groups of objects uniformly. It lets you write one interface for both files and folders, so you can perform actions on any item without worrying about its type. This simplifies code and scales naturally.

Before vs After
Before
if item is file:
    open_file(item)
else if item is folder:
    for child in item.children:
        open(child)
After
item.open()  # Works for both file and folder
What It Enables

It enables building flexible, tree-like structures where clients can treat individual and grouped objects the same way, making complex hierarchies easy to manage.

Real Life Example

File explorers use the Composite pattern to let users open, move, or delete files and folders seamlessly, no matter how deeply nested they are.

Key Takeaways

Composite pattern unifies handling of single and grouped objects.

Reduces code duplication and complexity in hierarchical structures.

Makes adding new components easier without changing client code.