You are on page 1of 2

Composite Tip i scop: ablon structural; cum se compun clasele i obiectele pentru a forma structuri mai mari; construie

te ierarhii arborescente de clase, de tip parte-ntreg; Solu ie: o clas abstract (Component) modeleaz simultan att obiectele primitive (Leaf), ct i obiectele compuse (Composite), ceea ce permite tratarea lor n mod uniform;

Participan i: Component: declararea interfe ei comune; Composite: define te comportamentul obiectelor compuse; Leaf: define te comportamentul obiectelor primitive; Exemplu:
#include <iostream> #include <vector> using namespace std; // create an common interface class IComponent { public: virtual void traverse() = 0; }; // leaf class Leaf: public IComponent { int value; public: Leaf(int val) : value(val){} void traverse() { cout << value << ' '; } };

// composite class Composite: public IComponent { vector<IComponent*> childrens; int value; public: Composite(int val) : value(val){} void add(IComponent* oneChildren) { childrens.push_back(oneChildren); } void traverse() { cout << value << " "; int nChildrens = childrens.size(); for (int i = 0; i < nChildrens ; i++) { childrens[i]->traverse(); } } }; class Row: public Composite { public: Row(int val): Composite(val){} void traverse() { cout << "Row"; Composite::traverse(); } }; class Column: public Composite { public: Column(int val): Composite(val){} void traverse() { cout << "Column"; Composite::traverse(); } }; int main() { Row firstRow(1); Column secondColumn(2); Column thirdColumn(3); Row fourthRow(4); Row fifthRow(5); firstRow.add( &secondColumn ); firstRow.add( &thirdColumn ); thirdColumn.add( &fourthRow ); thirdColumn.add( &fifthRow ); firstRow.add(&Leaf(6)); secondColumn.add(&Leaf(7)); thirdColumn.add(&Leaf(8)); fourthRow.add(&Leaf(9)); fifthRow.add(&Leaf(10)); firstRow.traverse(); cout << endl; return 0; } // Row1 // | // +-- Col2 // | | // | +-- 7 // | | // +-- Col3 // | | // | | // | +-- Row4 // | | | // | | | // | | +-- 9 // | | | // | +-- Row5 // | | | // | | | // | | +-- 10 // | +-- 8 // | | // +-- 6

You might also like