Java Reference
In-Depth Information
28. }
29.
30. public void setName(String newName){ name = newName; }
31. public void setOwner(Contact newOwner){ owner = newOwner; }
32. public void setTimeRequired(double newTimeRequired){ timeRequired = newTimeRequired; }
33.
34. public void addProjectItem(ProjectItem element){
35. if (!projectItems.contains(element)){
36. projectItems.add(element);
37. }
38. }
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 A.157
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 A.158
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 A.159
SupportedProjectItem.java
1. import java.util.ArrayList;
2. import java.io.File;