Recall UML diagram illustrating the general composite pattern.
In many situations, an operation may call on "helper" operations on the sub-components to carry out the task. The coding pattern for an operation that requires a helper is as follows.
class Composite extends AComponent {
// fields and sub-components.
public Object doTask (Object input) {
// Process the input parameter and the data fields to obtain a temporary
result needed by the sub-components to help complete the task:
Object temp = process (data fields, input);
// Pass the temporary result to each of the sub-components asking each of
them to "help" complete the task:
Object pr1 = _part1.helpDoTask (temp); //
partial result 1.
Object pr2 = _part2.helpDoTask
(temp);
// etc...
Object prN = _partN.helpDoTask
(temp);
//
Reassemble the partial results computed by the sub-components to obtain the
final result:
return putTogether (pr1, pr2, ..., prN);
}
protected Object helpDoTask (Object input) {
// Process the input parameter and the data fields to obtain a temporary
result needed by the sub-components to help complete the task:
Object temp = processPartial (data fields, input);
// Pass the temporary result to each of the sub-components asking each of
them to "help" complete the task:
Object pr1 = _part1.helpDoTask (temp); //
partial result 1.
Object pr2 = _part2.helpDoTask
(temp);
// etc...
Object prN = _partN.helpDoTask
(temp);
//
Reassemble the partial results computed by the sub-components to obtain the
final result:
return putTogetherPartial (pr1, pr2, ..., prN);
}
}
class Basic extends AComponent {
// fields
public Object doTask (Object input) {
// Process the input parameter and the data fields to obtain the result:
return simpleProcess (data fields, input);
}
protected Object helpDoTask (Object input) {
// Process the input parameter and the data fields to obtain the result:
return simpleProcessPartial (data fields, input);
}
}
For the list structure, the methods getMin(), everyOther(), and getLen() illustrate the above coding pattern. Note however that everyOther() and helpEveryOther() are mutually recursive. Click here to see the code.
D. X. Nguyen, last revised 01/29/02 Dung X. Nguyen - Copyright 2002 - All rights reserved