Java Reference
In-Depth Information
39. public void removeProjectItem(ProjectItem element){
40. projectItems.remove(element);
41. }
42.
43. public String toString(){
44. return "Task: " + name;
45. }
46. }
It's time to introduce a decorator to extend the basic capabilities of these classes. The class
ProjectDecorator
will provide the central ability to augment
Task
and
Deliverable
.
Example 3.17
ProjectDecorator.java
1. public abstract class ProjectDecorator implements ProjectItem{
2. private ProjectItem projectItem;
3.
4. protected ProjectItem getProjectItem(){ return projectItem; }
5. public void setProjectItem(ProjectItem newProjectItem){ projectItem = newProjectItem; }
6.
7. public double getTimeRequired(){
8. return projectItem.getTimeRequired();
9. }
10. }
The
ProjectDecorator
implements the
ProjectItem
interface and maintains a variable for another
ProjectItem
, which represents the “decorated” element. Note that
ProjectDecorator
delegates the
getTimeRequired
method to its internal element. This would be done for any method that would depend on the
functionality of the underlying component. If a
Task
with a required time of five days were decorated, you would
still expect it to return a value of five days, regardless of any other capabilities it might have.
There are two subclasses of
ProjectDecorator
in this example. Both demonstrate a way to add some extra
feature to project elements. The
DependentProjectItem
class is used to show that a
Task
or
Deliverable
depends on another
ProjectItem
for completion.
Example 3.18
DependentProjectItem.java
1. public class DependentProjectItem extends ProjectDecorator{
2. private ProjectItem dependentItem;
3.
4. public DependentProjectItem(){ }
5. public DependentProjectItem(ProjectItem newDependentItem){
6. dependentItem = newDependentItem;
7. }
8.
9. public ProjectItem getDependentItem(){ return dependentItem; }
10.
11. public void setDependentItem(ProjectItem newDependentItem){ dependentItem =
newDependentItem; }
12.
13. public String toString(){
14. return getProjectItem().toString() + EOL_STRING
15. + "\tProjectItem dependent on: " + dependentItem;
16. }
17. }
SupportedProjectItem
decorates a
ProjectItem
, and keeps an
ArrayList
of supporting documents—file
objects that represent additional information or resources.
Example 3.19
SupportedProjectItem.java
1. import java.util.ArrayList;
2. import java.io.File;
3. public class SupportedProjectItem extends ProjectDecorator{
4. private ArrayList supportingDocuments = new ArrayList();
5.
6. public SupportedProjectItem(){ }
7. public SupportedProjectItem(File newSupportingDocument){
8. addSupportingDocument(newSupportingDocument);
9. }
10.
11. public ArrayList getSupportingDocuments(){
12. return supportingDocuments;
13. }