Composite Design Pattern in .NET

The Composite pattern allows you to treat individual objects and groups of objects (composites) in a uniform way. It represents part-whole hierarchies so that client code can interact with both single and grouped items through a common interface.

 

Purpose

To build complex tree-like structures where leaf nodes (single elements) and composite nodes (groups) can be treated the same way.

 

Key Characteristics

  • Defines a component interface for both leaf and composite
  • Leaf handles base operations
  • Composite stores child components and delegates operations

 

Pros

  • Simplifies client code by treating all components uniformly
  • Supports hierarchical and recursive structures
  • Easy to add new types of components

 

Cons

  • Can make the system overly general
  • Harder to restrict certain operations for leaf-only or composite-only

 

Use Cases

  • Hierarchical account groups or financial portfolios
  • Nested reports or summary breakdowns
  • Composite transaction batches or multi-step approvals

 

Real-Time Finance Example: Portfolio with Individual and Grouped Assets

Let’s say you want to represent a portfolio that can include individual investments (like stocks) and groups of investments (like mutual funds or ETFs). Composite pattern fits this structure perfectly.

 

1. Define the Component Interface

public interface IInvestment

{

    void ShowDetails(int indent = 0);

}

 

2. Create Leaf – Individual Investment

public class Stock : IInvestment

{

    private readonly string _name;

    private readonly decimal _value;

 

    public Stock(string name, decimal value)

    {

        _name = name;

        _value = value;

    }

 

    public void ShowDetails(int indent = 0)

    {

        Console.WriteLine($"{new string(' ', indent)}Stock: {_name}, Value: ₹{_value}");

    }

}

 

3. Create Composite – Investment Group

public class InvestmentGroup : IInvestment

{

    private readonly string _groupName;

    private readonly List<IInvestment> _investments = new();

 

    public InvestmentGroup(string groupName)

    {

        _groupName = groupName;

    }

 

    public void Add(IInvestment investment)

    {

        _investments.Add(investment);

    }

 

    public void ShowDetails(int indent = 0)

    {

        Console.WriteLine($"{new string(' ', indent)}Group: {_groupName}");

 

        foreach (var investment in _investments)

        {

            investment.ShowDetails(indent + 4);

        }

    }

}

 

4. Client Code Usage

class Program

{

    static void Main()

    {

        var stock1 = new Stock("Tata Motors", 1500);

        var stock2 = new Stock("Infosys", 3200);

        var stock3 = new Stock("Reliance", 5400);

 

        var smallCapFund = new InvestmentGroup("Small Cap Fund");

        smallCapFund.Add(stock1);

        smallCapFund.Add(stock2);

 

        var largeCapFund = new InvestmentGroup("Large Cap Fund");

        largeCapFund.Add(stock3);

 

        var fullPortfolio = new InvestmentGroup("Full Portfolio");

        fullPortfolio.Add(smallCapFund);

        fullPortfolio.Add(largeCapFund);

 

        fullPortfolio.ShowDetails();

    }

}

 

Output

Group: Full Portfolio

    Group: Small Cap Fund

        Stock: Tata Motors, Value: ₹1500

        Stock: Infosys, Value: ₹3200

    Group: Large Cap Fund

        Stock: Reliance, Value: ₹5400

 

Summary

  • The Composite Pattern is perfect for tree-like or nested structures
  • In finance, it’s ideal for portfolios, tax breakdowns, investment bundles, or reporting hierarchies
  • Allows treating individual and grouped elements uniformly, simplifying client logic

 

 

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced