Java Reference
In-Depth Information
“Look but don't touch” views - Not all views require a controller. Some provide only a visual representation of
model data, but don't support any changes to the model from that view.
Related Patterns
Related patterns include the following:
Observer (page 94) - The MVC pattern often uses the Observable pattern to manage communication. This is
usually done for the following parts of the system:
Between the view and controller, so that a change in the view triggers a response in the controller
Between the model and view, so the view is notified of a change in the model.
Strategy (page 114) - The controller is often implemented with the Strategy pattern to simplify changing
controllers.
Example
Note:
For a full working example of this code example, with additional supporting classes and/or a RunPattern class,
see “ Model-View-Controller (MVC) ” on page 501 of the “ Full Code Examples ” appendix.
This code example provides a component-level MVC pattern to manage a contact in the Personal Information
Manager. The ContactModel class provides the model for this demonstration, in this case storing the contact's
first name, last name, title and organization.
Example 4.1 ContactModel.java
1. import java.util.ArrayList;
2. import java.util.Iterator;
3. public class ContactModel{
4. private String firstName;
5. private String lastName;
6. private String title;
7. private String organization;
8. private ArrayList contactViews = new ArrayList();
9.
10. public ContactModel(){
11. this(null);
12. }
13. public ContactModel(ContactView view){
14. firstName = "";
15. lastName = "";
16. title = "";
17. organization = "";
18. if (view != null){
19. contactViews.add(view);
20. }
21. }
22.
23. public void addContactView(ContactView view){
24. if (!contactViews.contains(view)){
25. contactViews.add(view);
26. }
27. }
28.
29. public void removeContactView(ContactView view){
30. contactViews.remove(view);
31. }
32.
33. public String getFirstName(){ return firstName; }
34. public String getLastName(){ return lastName; }
35. public String getTitle(){ return title; }
36. public String getOrganization(){ return organization; }
37.
38. public void setFirstName(String newFirstName){ firstName = newFirstName; }
39. public void setLastName(String newLastName){ lastName = newLastName; }
40. public void setTitle(String newTitle){ title = newTitle; }
Search WWH ::




Custom Search