/** * composite.h * Implemented by Blueprint Technologies, Inc. */ #ifndef _composite_h #define _composite_h #include using namespace std; /** * Declares the interface for objects in the composition. Implements * default behavior for the interface common to all classes, as * appropriate. Declares an interface for accessing and managing its * child components. */ class Component { public: virtual void operation() = 0; virtual void add( Component* ) { }; virtual void remove( Component* ) { }; virtual Component* getChild( int ) { return (Component *) 0; }; }; /** * Represents leaf objects in the composition. A leaf has no children. * Defines behavior for primitive objects in the composition. */ class Leaf: public Component { public: virtual void operation() { // do something here. }; }; /** * Defines behavior for components having children. Stores child components. * Implements child-related operations in the Component interface. */ class Composite: public Component { private: vector< Component* > children; public: virtual void operation() { for( int x = 0; x < children.size(); ++x ) { Component* component = children[x]; component -> operation(); } }; virtual void add( Component* obj ) { children.push_back( obj ); }; virtual void remove( Component* obj ) { vector< Component* >::iterator i; int found; while( 1 ) { found = 0; for( i = children.begin(); i != children.end(); ++i ) { if( *i == obj ) { found = 1; children.erase( i ); break; } } if( found == 0 ) { break; } } }; virtual Component* getChild( int index ) { return children[ index ]; }; }; #endif