Object Oriented Programming Patterns for Geeks

The Composite Pattern

 

namespace ooppatterns
{
    using System;
    using System.Collections.Generic;

    internal class Program
    {
        private static void Main( string[] args )
        {
            Branch root = new Branch( "Menu" );
            root.Add( new Leaf( "Option 1" ) );
            root.Add( new Leaf( "Option 2" ) );

            Branch b1 = new Branch( "Submenu A" );
            b1.Add( new Leaf( "Option A 1" ) );

            Branch b2 = new Branch( "Submenu B" );
            b2.Add( new Leaf( "Option B 1" ) );
            b2.Add( new Leaf( "Option B 2" ) );
            b2.Add( new Leaf( "Option B 3" ) );

            b1.Add( b2 );
            b1.Add( new Leaf( "Option A 2" ) );
            b1.Add( new Leaf( "Option A 2" ) );

            root.Add( b1 );
            root.Add( new Leaf( "Option 3" ) );

            root.Render( 0 );

            Console.ReadLine();
        }
    }

    interface INode
    {
        void Render( int indent );
    }

    class Branch : List<INode>, INode
    {
        private string _name;

        public Branch( string name )
        {
            this._name = name;
        }

        public void Render( int indent )
        {
            Console.WriteLine( new String( '\t', indent ) + this._name );

            foreach ( INode component in this )
                component.Render( indent + 1 );
        }
    }

    class Leaf : INode
    {
        private string _name;

        public Leaf( string name )
        {
            this._name = name;
        }

        public void Render( int indent )
        {
            Console.WriteLine( new String( '\t', indent ) + this._name );
        }
    }
}