Scan with Phone

Scan to instantly open and share this page on your mobile device.

Link copied to clipboard!

Composite

Treat leaves and groups uniformly via shared interface.

C#

interface IComponent
{
    int Sum();
}
class Leaf : IComponent
{
    int v;
    public Leaf(int x)
    {
        v = x;
    }
    public int Sum()
    {
        return v;
    }
}
class Node : IComponent
{
    List children = new();
    public void Add(IComponent c)
    {
        children.Add(c);
    }
    public int Sum()
    {
        return children.Sum(c => c.Sum());
    }
}
var root = new Node();
root.Add(new Leaf(3));
var sub = new Node();
sub.Add(new Leaf(2));
sub.Add(new Leaf(5));
root.Add(sub);
int total = root.Sum(); // 10
next