Tutorials Design Patterns in C#
Composite Pattern — Complete Guide
Composite Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 8 of 69
Composite Pattern
GoF Core → Enterprise → Cloud & Craft
GoF Core · 1 — Create & structure · ~6 min · Module 2: Structural Design Patterns
What is this?
Composite lets you treat individual objects and trees of objects uniformly — folders of items sharing one interface.
Why should you care?
ShopNest category menus nest categories and leaf products under one render API.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
public interface IMenuNode { void Print(int indent = 0); }
public sealed class MenuItem : IMenuNode
{
private readonly string _name;
public MenuItem(string name) => _name = name;
public void Print(int indent = 0) => Console.WriteLine($"{new string(' ', indent)}- {_name}");
}
public sealed class MenuGroup : IMenuNode
{
private readonly string _name;
private readonly List<IMenuNode> _children = new();
public MenuGroup(string name) => _name = name;
public void Add(IMenuNode n) => _children.Add(n);
public void Print(int indent = 0)
{
Console.WriteLine($"{new string(' ', indent)}[{_name}]");
foreach (var c in _children) c.Print(indent + 2);
}
}
var root = new MenuGroup("Catalog");
root.Add(new MenuItem("Phones"));
var audio = new MenuGroup("Audio");
audio.Add(new MenuItem("Headphones"));
root.Add(audio);
root.Print();
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- MenuGroup and MenuItem both build IMenuNode.
- Print recurses.
- Callers do not care if a node is leaf or branch.
Practice next
- Print the sample tree.
- Add another nested group.
- Count leaves with a recursive helper.
- Add Remove on MenuGroup.
- Print SKU counts per group.
Remember
Uniform tree interface. Leaves and composites. Recursive operations.
ShopNest nested categories
Admin renders category trees with one Print/Walk API.
Outcome: UI code stays simple for deep menus.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!