Composite Pattern in C# – Real-Time Example (Tree-Like Structures)

What is Composite Pattern?

The Composite Pattern is a structural design pattern that allows you to treat individual objects and groups of objects uniformly.

It is mainly used for hierarchical/tree-like structures.


Why Use Composite Pattern?

  • Simplify hierarchical data handling
  • Treat single and grouped objects the same way
  • Enable recursive operations
  • Reduce conditional complexity

Real-Time Scenario

Examples:

  • Folder → contains files & subfolders
  • Invoice → contains multiple items
  • Shopping cart → contains products & bundles

👉 Single item and group item behave similarly.


Real-Time Example – Invoice Items System


Step 1: Component Interface

public interface IComponent
{
    decimal GetPrice();
}

Step 2: Leaf Object (Single Item)

public class Product : IComponent
{
    private readonly decimal _price;

    public Product(decimal price)
    {
        _price = price;
    }

    public decimal GetPrice()
    {
        return _price;
    }
}

Step 3: Composite Object (Group)

public class ProductGroup : IComponent
{
    private readonly List<IComponent> _items = new();

    public void Add(IComponent item)
    {
        _items.Add(item);
    }

    public decimal GetPrice()
    {
        return _items.Sum(x => x.GetPrice());
    }
}

Usage Example

// Single products
var product1 = new Product(500);
var product2 = new Product(300);

// Group of products
var group = new ProductGroup();
group.Add(product1);
group.Add(product2);

// Main invoice/cart
var invoice = new ProductGroup();
invoice.Add(group);
invoice.Add(new Product(200));

Console.WriteLine(invoice.GetPrice());

Output

1000

Key Concept

Instead of:

if(item is Product)
{
    ...
}
else if(item is ProductGroup)
{
    ...
}

We do:

item.GetPrice();

👉 Same method works for both single object and group.


Diagram Understanding

IComponent
   ↑
-------------------
|                 |
Product      ProductGroup
                  ↓
          Contains IComponent

👉 Composite can contain leafs or other composites.


Recursive Structure Example

Folder
 ├── File
 ├── File
 └── SubFolder
       ├── File
       └── File

👉 Composite Pattern is perfect for this.


Advantages

  • ✔ Reduces complexity
  • ✔ Improves flexibility
  • ✔ Promotes reusable structures
  • ✔ Easier maintenance
  • ✔ Uniform handling of objects

Disadvantages

  • ✖ Can increase number of classes
  • ✖ Harder to understand initially
  • ✖ Over-engineering for simple apps

When to Use

Use Composite Pattern when:

  • Working with hierarchical/tree-like data
  • Need recursive structures
  • Want uniform handling of objects
  • Groups and single objects behave similarly

Real Project Mapping (.NET + Angular)

Feature Usage
Invoice items Composite
Shopping cart Composite
Folder/file explorer Composite
Menu systems Composite
Category hierarchy Composite

ASP.NET Core Real Example

Menu tree:

Menu
 ├── Dashboard
 ├── Reports
 │     ├── Sales
 │     └── Finance

👉 Composite structure.


Advanced Example – Nested Invoice

Bundle
 ├── Product A
 ├── Product B
 └── Mini Bundle
       ├── Product C
       └── Product D

👉 Total price calculated recursively.


Pro Tip

Composite Pattern works well with:

  • Recursion
  • Tree structures
  • LINQ aggregations
  • Angular recursive components

Summary

Composite Pattern helps you:

  • Handle hierarchical structures easily
  • Treat groups and single objects uniformly
  • Simplify recursive logic

👉 Perfect for:

  • Invoice systems
  • Folder structures
  • Shopping carts
  • Nested menus

Comments

Popular posts from this blog

Promises in Angular

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Csharp Coding - Session