Used to implement a hierarchy of components, with leaves, a root, and subtrees. Client calls to a component function recursively call the same function for its sub-components, or just the function for itself if the call is on a leaf node.
Use when:
Example C++ Code
// component interface (root type)
class Equipment
{
public:
virtual ~Equipment();
const char* Name() { return m_name; }
// the 'operation' that all components have
virtual Currency Price();
// provides tree structure util funcs
virtual void Add(Equipment*);
virtual void Remove(Equipment*);
virtual Iterator<Equipment*>* CreateIterator(); // for traversing all children
protected:
Equipment(const char*);
private:
const char* m_name;
};
// a leaf node type that has no sub-components
class FloppyDisk : public Equipment
{
public:
FloppyDisk(const char*);
virtual ~FloppyDisk();
// 'Operation()' implementation
virtual Currency Price();
};
// the Composite which contains sub-components
class CompositeEquipment : public Equipment
{
public:
// will iterate and add price of all sub-children
virtual Currency Price()
{
Iterator<Equipment*>* i = CreateIterator();
Currency total = 0;
for (i->First(); !i->IsDone(); i++)
{
total += i->CurrentItem()->Price();
}
delete i;
return total;
}
// provides tree structure util funcs
virtual void Add(Equipment*);
virtual void Remove(Equipment*);
virtual Iterator<Equipment*>* CreateIterator(); // for traversing all children
protected:
CompositeEquipment(const char*);
private:
List<Equipment*>* m_equipment;
};
// implementation of a composite, parent node
class ComputerChassis : public CompositeEquipment
{
public:
ComputerChassis(const char*);
virtual ~ComputerChassis();
virtual Currency Price();
};