System Design ( Day - 55 )

Composite Design Pattern
Definition
Composite pattern composes object into tree like structure representing a part - whole hierarchy. It let client treats individual object and composition of object uniformly.
Design File System
When you have a tree-like structure—folders containing files and subfolders—the Composite Pattern lets you treat both “composite” (folders) and “leaf” (files) objects through a common interface. This makes your code simpler, more flexible, and easy to extend.
🎯 The Problem
Imagine you need to:
List all items in a folder
Open every file under a directory (including nested subfolders)
Compute the total size of a folder
You don’t want your client code to have special loops for files vs. folders. You’d rather call the same methods on both.
📂 File-System Example
📐 Standard UML Blueprint
Component: declares the common interface (
operation()
).Leaf: implements the basic behavior.
Composite: maintains a collection of
Component
children and implements operations by delegating to them.
🌟 Why Use Composite?
Uniformity: Treat single objects and compositions the same way.
Flexibility: Add new types of
Component
(e.g.,ShortcutItem
) without changing existing client code.Simplicity: Clients call one API (
ls()
,openAll()
,getSize()
) instead of branching on type.
Subscribe to my newsletter
Read articles from Manoj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
