[ fromfile: children.xml id: children ]
Figure 8.2 describes the Composite pattern.
In this diagram, there are two distinct classes for describing two roles.
A composite object is something that can contain children.
A component object is something that can have a parent.
Many Qt classes use the Composite pattern: QObject, QWidget, QTreeWidgetItem, QDomNode, QHelpContentItem, QResource. The Composite pattern can be found in just about any tree-based structure.
In Figure 8.3, you can see that QObject is both composite and component.
The simplest QObject
s (i.e., the leaf nodes of this tree) each have a parent but no children.
Client code can recursively deal with each node of the tree.
Figure 8.4 shows an abbreviated and simplified subchart of today's Suffolk University.
Each box in this chart is a component.
It may be a composite and have subcomponents which, in turn, may be composite or simple components.
Each leaf of this tree is an individual employee of the organization.
You can use the Composite pattern to model this structure.
Each node of the tree can be represented by an object of type OrgUnit
.
class OrgUnit : public QObject { public: QString getName(); double getSalary(); private: QString m_Name; double m_Salary; };
For each OrgUnit
pointer ouptr
in the tree, initialize its m_Salary
data member as follows:
If ouptr
points to an individual employee, use that employee's actual salary.
Otherwise initialize it to 0.
You can implement the getSalary()
method like this:
double OrgUnit::getSalary() {
QList<OrgUnit*> childlst = findChildren<OrgUnit*>();
double salaryTotal(m_Salary);
if(!childlst.isEmpty())
foreach(OrgUnit* ouptr, childlst)
salaryTotal += ouptr->getSalary();
return salaryTotal;
}
A call to getSalary()
from any particular node returns the total salary for the part of the university represented by the subtree whose root is that node.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |