Composite
Composes objects into tree structures and treats them uniformly as if they were individual objects.
Context
Your model is hierarchical: folders with files and subfolders, groups of figures, nested comments.
Problem
You want to treat leaves and composites with the same code (e.g., CalculateSize()).
Solution
A common interface (IFileSystemEntry) implemented by leaves (File) and composites (Directory) which delegates recursively.
#Example in C#
public interface IFileSystemEntry { long GetSize(); }
public class File : IFileSystemEntry
{
public long Size { get; init; }
public long GetSize() => Size;
}
public class Directory : IFileSystemEntry
{
private readonly List<IFileSystemEntry> _children = new();
public void Add(IFileSystemEntry e) => _children.Add(e);
public long GetSize() => _children.Sum(c => c.GetSize()); // recursive and uniform
}When NOT to use it
When leaves and composites have divergent behaviors that force branches (if (isFolder)).
Tradeoffs
| Pro | Con |
|---|---|
| Uniform client | Difficult to restrict child types in the common interface |
#structural #gof #tree