Info

Figure 7-1. Example of delegation.

Figure 7-1 shows that class ClassDelegator is associated with class ClassDelegate through a unidirectional association. Therefore, ClassDelegator has access to data and behavior of ClassDelegate; an attribute of type ClassDelegate is defined in the ClassDelegator that points to ClassDelegate. Thus, the behavior of ClassDelegator can be extended by using the behavior of ClassDelegate.

Let us consider a concrete example of using the pattern of delegation. Figure 7-2 shows the relationships between classes in simple Plant component.

Figure 7-2. Example of delegation.

As explained in section Components, the functionalities provided by the component Plant are defined by interface Plantlnterface. To make things simple, we will consider that Plantlnterface defines only one method, getLeafArealndexQ. As shown in Figure 7-2, Plant component is composed of a few classes, such as LeafSystem, RootSystem, and StemSystem. These classes are provided with data and behavior to play the role of leaf, stem, and root systems of the plant. Although these classes have a well-defined role, none of them communicates directly with other classes or components of the system. In the case that some other class/component of the system would require to use behavior defined in class LeafSystem, the communication will occur through class Plant. Plant has access to data and behavior of classes LeafSystem, RootSystem, and StemSystem, through attributes leafSystem, rootSystem, and stemSystem that hold references to objects of the corresponding classes.

When another class or component needs to use the value of leaf area index parameter that is stored in an object of class LeafSystem, it needs to send the message getLeafArealndexQ to an object of type Plant. This object knows how to respond to this message as it implements Plantlnterface. Or the calculations for the leaf area index parameter are defined in LeafSystem, not in Plant. Plant will delegate the call to LeafSystem using the attribute leafSystem. After the calculations are terminated, Plant will return the results to the requestor object.

Figure 7-3 shows the implementation in Java of the delegation pattern. Lines 3, 4, and 5 define attributes of Plant that point to objects of type LeafSystem, RootSystem and StemSystem. Lines 7 through 9 define method getLeafArealndexQ. Class Plant provides an implementation for this method as it implements Plantlnterface. As shown in line 8, Plant delegates the method call to LeafSystem, meaning that method getLeafArealndexQ defined in Plant will return the result of the execution of the same method defined in class LeafSystem.

1 public class Plant implements Plantlnterface {

0 0

Post a comment