Java Reference
In-Depth Information
Behavioral Pattern Code Examples
Chain of Responsibility
The PIM can act as a project manager as well as a contact manager. This code example shows how to use the Chain of
Responsibility pattern to retrieve information from within a project hierarchy.
The ProjectItem interface defines common methods for anything that can be part of a project.
Example A.32 ProjectItem.java
1. import java.io.Serializable;
2. import java.util.ArrayList;
3. public interface ProjectItem extends Serializable{
4. public static final String EOL_STRING = System.getProperty("line.separator");
5. public ProjectItem getParent();
6. public Contact getOwner();
7. public String getDetails();
8. public ArrayList getProjectItems();
9. }
The interface defines the methods getParent , getOwner , getDetails , and getProjectItems . Two classes
implement ProjectItem in this example — Project and Task . The Project class is the base of a project, so its
getParent method returns null. The getOwner and getDetails method returns the overall owner and details for
the project, and the getProjectItems method returns all of the project's immediate children.
Example A.33 Project.java
1. import java.util.ArrayList;
2. public class Project implements ProjectItem{
3. private String name;
4. private Contact owner;
5. private String details;
6. private ArrayList projectItems = new ArrayList();
7.
8. public Project(){ }
9. public Project(String newName, String newDetails, Contact newOwner){
10. name = newName;
11. owner = newOwner;
12. details = newDetails;
13. }
14.
15. public String getName(){ return name; }
16. public String getDetails(){ return details; }
17. public Contact getOwner(){ return owner; }
18. public ProjectItem getParent(){ return null; }
19. public ArrayList getProjectItems(){ return projectItems; }
20.
21. public void setName(String newName){ name = newName; }
22. public void setOwner(Contact newOwner){ owner = newOwner; }
23. public void setDetails(String newDetails){ details = newDetails; }
24.
25. public void addProjectItem(ProjectItem element){
26. if (!projectItems.contains(element)){
27. projectItems.add(element);
28. }
29. }
30.
31. public void removeProjectItem(ProjectItem element){
32. projectItems.remove(element);
33. }
34.
35. public String toString(){
36. return name;
37. }
38. }
The Task class represents some job associated with the project. Like Project , Task can keep a collection of
subtasks, and its getProjectItems method will return these objects. For Task , the getParent method returns the
parent, which will be another Task or the Project .
Example A.34 Task.java
 
 
Search WWH ::




Custom Search