SOLID & Design Patterns Interview Question #56

What is the Composite Pattern?

Advanced Patterns, CQRS & Domain-Driven Design Fundamentals Mid-Level Intermediate

Quick Interview Answer

The Composite Pattern represents individual objects and groups of objects through a common abstraction. Clients can therefore treat a single element and a collection of elements uniformly.

Detailed Explanation

The Composite Pattern represents individual objects and groups of objects through a common abstraction. Clients can therefore treat a single element and a collection of elements uniformly.

It is especially useful for tree structures such as menus, folders, organizational hierarchies, UI components, or nested categories.

Code Example

public interface INode
{
    int GetSize();
}

public class Folder : INode
{
    public List<INode> Children { get; } = new();

    public int GetSize()
        => Children.Sum(x => x.GetSize());
}