// Purpose.  Composite design pattern demo.
//
// Discussion.  Recursive composition has been encapsulated in an
// inheritance hierarchy.  The Composite class "hasa" relationship up the
// "isa" hierarchy (it couples itself only to the abstract base class
// Component).  Composite objects may contain Leaf objects and/or other
// Composites.  Methods may be defined on the class hierarchy that are
// capable of treating a heterogeneous aggregation of objects uniformly.


#include <iostream.h>


class Component {
public:
   virtual void traverse() = 0;
};


class Leaf : public Component {
public:
   Leaf( int val ) : value_(val)  { }
   void traverse()                { cout << value_ << " "; }
private:
   int  value_;
};


class Composite : public Component {
public:
   Composite() : index_( 0 )   { }
   void add( Component* ele )  { children_[index_++] = ele; }
   void traverse()
   {
      for (int i=0; i < index_; i++)
         children_[i]->traverse();
   }
private:
   Component*  children_[99];
   int         index_;
};


main()
{
   Composite  containers[4];

   for (int i=0; i < 4; i++)
   {
      containers[i].add( new Leaf( 2 * i ) );
      containers[i].add( new Leaf( 2 * i + 1 ) );
   }

   containers[0].add( &(containers[3]) );
   containers[0].add( &(containers[2]) );
   containers[0].add( &(containers[1]) );

   for (i=0; i < 4; i++) {
      containers[i].traverse();   cout << endl; }
}

// 0 1 6 7 4 5 2 3 
// 2 3 
// 4 5 
// 6 7 

