DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

C# Design Pattern: Composite

The Composite pattern is used when you have objects that can be organized into hierarchical structures, like trees. It allows you to treat individual objects and compositions of objects the same way. A practical example would be a file system, where folders can contain files or other folders, and you want to perform operations on either in a uniform way.

C# Code Example:

// Base component
public interface IComponent
{
    void Display();
}

// Leaf object (a file, for example)
public class File : IComponent
{
    private string _name;

    public File(string name)
    {
        _name = name;
    }

    public void Display()
    {
        Console.WriteLine($"File: {_name}");
    }
}

// Composite object (a folder, for example)
public class Folder : IComponent
{
    private string _name;
    private List<IComponent> _components = new List<IComponent>();

    public Folder(string name)
    {
        _name = name;
    }

    public void Add(IComponent component)
    {
        _components.Add(component);
    }

    public void Display()
    {
        Console.WriteLine($"Folder: {_name}");
        foreach (var component in _components)
        {
            component.Display();
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Create files and folders
        File file1 = new File("file1.txt");
        File file2 = new File("file2.txt");

        Folder folder1 = new Folder("Documents");
        folder1.Add(file1);
        folder1.Add(file2);

        // Display folder structure
        folder1.Display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In the example, File is a simple object (leaf), while Folder can contain other files or folders (composite). Both implement the IComponent interface, allowing them to be treated uniformly. In the main code, a folder is created containing two files, and the structure is displayed hierarchically.

Conclusion:

The Composite pattern is useful when dealing with hierarchical structures like file systems or navigation menus, allowing you to treat simple objects and compositions of objects in the same way.

Source code: GitHub

Top comments (0)