Java Reference
In-Depth Information
managerJane.addEmployee(programmerAimee);
managerJane.addEmployee(programmerSeppe);
showOrganigram(managerWiley);
}
public static void showOrganigram(Employee e) {
showOrganigram(e, 1);
}
private static void showOrganigram(Employee e, int level) {
// Recursive function, show employee
System.out.format("%"+(level*2)+"s - %s, " +
"earning %s", "", e.getName(), e.getSalary());
if (e.getNrEmployees() > 0)
System.out.format(" manages %s employees:", e.getNrEmployees());
System.out.println();
for (int i = 0; i < e.getNrEmployees(); i++) {
showOrganigram(e.getEmployee(i), level+1);
}
}
}
Running this code prints the following:
- Wiley, earning 35000.0 manages 2 employees:
- Jane, earning 30000.0 manages 2 employees:
- Aimee, earning 16000.0
- Seppe, earning 14000.0
- Bart, earning 15000.0
Here you can see the benefits of the composite pattern in action. In the recursive function, you
don't need to pay attention to the differences among a programmer, manager, and groups of
employees, as you can apply the same methods on all of them, using the single, abstract Employee
class.
Note that there is also a second way to model a composite pattern: by having both the composite
objects (the objects containing a list) and the member objects (objects without a list) implement a
component interface that defines the operations that should be possible on both of them. It would
use the following structure:
public interface Component {
public void method1();
public void method2();
// ...
}
public class Member implements Component {
@Override
public void method1() {/*...*/}
@Override
public void method2() {/*...*/}
// Other methods
}
Search WWH ::




Custom Search