Tutorials Design Patterns Mastery

Composite Pattern: Managing tree structures & hierarchies

On this page

The Composite Pattern

The Composite Pattern allows you to treat individual objects and "Groups of Objects" (Composites) identically. This is the standard pattern for building File Systems (Files vs Folders), Organizational Charts (Employee vs Manager), or UI Component Trees.

1. Scenario: File System Size

If you ask for the size of a File, it returns its bytes. If you ask for the size of a Folder, it internally asks all its children for their sizes and sums them up. To the user, they both look like an IFileSystemItem.

public interface IComponent { void Display(); }

public class Leaf : IComponent { ... } // Individual item

public class Composite : IComponent 
{
    private List<IComponent> _children = new();
    
    public void Display() 
    {
        foreach(var child in _children) child.Display();
    }
}

2. Recursive Logic

The Composite pattern relies heavily on Recursion. A Composite can contain another Composite, allowing for infinitely deep "Tree" structures.

4. Interview Mastery

Q: "Is the Composite pattern a violation of the Interface Segregation Principle (ISP)?"

Architect Answer: "It can be. If you put `Add(child)` and `Remove(child)` methods on the top-level `IComponent` interface, the 'Leaf' node is forced to implement those methods even though it cannot have children. This is a trade-off. You lose **Safety** (because a Leaf might throw an exception if you try to add a child), but you gain **Transparency** (because you can treat every node exactly the same without checking if it is a list or an object). Senior architects usually choose transparency for cleaner client code."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns Mastery
Course syllabus
1. Introduction to Design Patterns
2. Creational Patterns
3. Structural Patterns
4. Behavioral Patterns
5. Modern Enterprise & Cloud Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details